我有一个简单的Tkinter窗口,显示生产线是上升还是下降,以及是否停机多长时间。但是,我无法弄清楚如何更新每行的标签。我尝试使用.after()
检查更改,然后调用create_label()
,但它只是添加了另一个标签,并且调用root.update_idletasks()
没有做任何事情。我也尝试过使用StringVar()
,但我也无法做到这一点。
import Tkinter as tk
import tkFont
import time
class Line():
def __init__(self, line_name):
self.name = line_name
self.label = None
self.start = None
def get_down_time(self):
#return status of line
if self.start:
return time.clock()-self.start, 'red'
else:
return 'Running', 'green'
def create_label(self, parent):
status, color = self.get_down_time()
font = tkFont.Font(family="FixedSys", size=8)
self.label = tk.Label(parent, text = '{:>7} {:>9}'.format(self.name+':', status), bg=color, fg='black', height = 1, justify=tk.LEFT, anchor=tk.NW, relief=tk.RAISED, font = font)
self.label.pack(fill=tk.X, expand=False)
def initUI(root, lines):
root.title("Line Status")
for line in lines.values(): #Create all labels
line.create_label(root)
def check_for_changes(lines, root):
inp = raw_input('>>> ').replace('\n','')
if inp in lines.keys(): #check if input is a line and update value if so
if lines[inp].start:
lines[inp].start = None
else:
lines[inp].start = time.clock()
#lines[inp].create_label(root) #Creates new label
#root.update_idletasks() #Does nothing
root.after(1000, check_for_changes, lines, root)
def main():
lines = {'1': Line('1'), '2': Line('2'), '3':Line('3')}
root = tk.Tk()
root.geometry("175x300+300+300")
initUI(root, lines) #create window with labels
root.after(1000, check_for_changes, lines, root)
root.mainloop()
if __name__ == '__main__':
main()
答案 0 :(得分:2)
每个行对象都有一个标签作为子项。您只需在标签对象上调用configure
即可进行更改。无需使用StringVar
:
lines[inp].label.configure(text="...", background="...")