如何在Python的tkinter中打印标签或ID
我正在使用tkinter来生成一个图形用户界面(GUI)。
from Tkinter import *
root = Tk()
root.title("explorer")
f=Canvas(root, width=1200, height=768)
f.grid()
main_line = f.create_line(200,300,300,300, tags="main_line_tag", width=5)
mainloop()
在上面的例子中,我想在这条线旁边打印标签和ID。我该怎么做呢?
更新
main_line = f.create_line(200,300,300,300, tags="main_line_tag", width=5)
tags_text = ', '.join(f.gettags(main_line))
line_text = "%s: %s" % (main_line, tags_text)
f.create_text(220,320, text=line_text)
解决方案有效,但我实际的需求是
f=Canvas(root, width=1200, height=768)
f.grid()
class Create:
def __init__(self,xy,t):
self.xy=self.xy
self.t=t
for i in range(1, self.t+1):
exec 'main_line%d = f.create_line(200,300,300,300, tags="main_line_tag%d")' %(i,i)
#end of class Create
def update(t,newxy):
for i in range(1,t+1):
exec'f.coord(main_line%d, *newxy)'%i
mainloop()
在上面的示例代码中,我试图在运行代码时更新这条线的坐标,但我收到了“main_line1未定义”的错误……标签也是一样。我该如何解决这个问题呢?
谢谢
1 个回答
1
只需要画一个文本项,然后用它的ID和gettags
这个画布的方法来创建你的文本。
main_line = f.create_line(200,300,300,300, tags="main_line_tag", width=5)
tags_text = ', '.join(f.gettags(main_line))
line_text = "%s: %s" % (main_line, tags_text)
f.create_text(220,320, text=line_text)
更新
使用exec 'main_line%d = ...
的问题在于,你虽然创建了这条线,但没有保存它的引用。不过,使用exec
并不是一个推荐的解决方案,还有其他简单的方法可以用列表来实现你想要的效果:
lines = []
def update(t, newxy):
for line in lines:
f.coord(line, *newxy)
class Create:
def __init__(self, xy, t):
self.xy = xy
self.t = t
for i in xrange(self.t):
new_line = f.create_line(200,300,300,300, tags="main_line_tag%d" % (i+1))
lines.append(new_line)