Найти - Пользователи
Полная версия: Как в Tkinter.Text определить имя нажатого тега?
Начало » GUI » Как в Tkinter.Text определить имя нажатого тега?
1
vkopey
Вот код:
# -*- coding: UTF-8 -*-
from Tkinter import *
import re

def fn(event):
print event.__dict__
#Как здесь определить имя нажатого тега?

def addTag(tag,start,end):
txt.tag_add(tag,'1.0+%dc'%start,'1.0+%dc'%end)
txt.tag_config(tag, background='yellow', foreground='blue')
txt.tag_bind(tag, '<Double-1>', fn)

tk = Tk()

txt = Text(tk,height=5,width=20,font='Arial 12',wrap=NONE)
txt.pack()
s='''#Line text ##1##
#Line ##text## 2
#Line text ##3##'''
txt.insert(END, s)
text = txt.get(1.0, 'end')
i=0
for mo in re.finditer(r"\#{2}.*?\#{2}", text):
addTag(i, mo.start(), mo.end())
i+=1

tk.mainloop()
ЗЫ:
1.Обязательно ли здесь всем тегам иметь разное имя?
2.Можно ли немного оптимизировать здесь алгоритм создания тегов? Или и так сойдет?
sp3
1. если они должны быть разные(стиль или бинды на них), то да
2.не знаю что вы делаете, но так может быть проще?
from Tkinter import *
from random import randint

def randomColor():
r = randint(1,250)
g = randint(1,250)
b = randint(1,250)
hexchars = "0123456789ABCDEF"
return "#" + hexchars[r / 16] + hexchars[r % 16] + hexchars[g / 16]\
+ hexchars[g % 16] + hexchars[b / 16] + hexchars[b % 16]


root = Tk()

textw = Text(root,font="Verdana 12 bold")
textw.pack(fill = "both",expand = 1)

text = u'каждый охотник желает знать где сидит фазан'

for x,word in enumerate(text.split()):
tagName = 'tag%s'%x
textw.tag_config(tagName, foreground = randomColor())
textw.tag_bind(tagName, "<Button-1>",lambda e,tagName=tagName:
textw.tag_config(tagName, foreground = randomColor()) )
textw.tag_lower(tagName)
textw.insert(END,word+' ',tagName)
root.mainloop()
vkopey
Спасибо, sp3
sp3
textw.tag_bind(tagName, "<Button-1>",lambda e,tagName=tagName: textw.tag_config(tagName,  foreground = randomColor()) )   
textw.tag_lower(tagName)
1.Здесь для каждого тега создается своя функция-обработчик “<Button-1>” ? Насколько это эффективно с точки зрения экономии памяти?
2.А зачем textw.tag_lower(tagName) ?
sp3
1. не так и много требуется памяти(в наше то время с парой гигабайт на борту)
2.tag_lower: если тегу назначить фоновый цвет, то при выделении мышью этот фон будет перекрывать выделение. Если выполнить tag_lower то выделятся будет нормально
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB