我有一个简单的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() 发布于 2016-02-15 15:00:31
每个行对象都有一个作为子对象的标签。您可以简单地调用label对象上的configure来更改它。没有必要使用StringVar
lines[inp].label.configure(text="...", background="...")https://stackoverflow.com/questions/35411940
复制相似问题