【发布时间】:2017-12-11 08:28:02
【问题描述】:
我正在使用 tkinter 创建我的第一个 GUI。我已经创建了几个类,但需要帮助。我正在尝试读取文件的一行,使用标签将其显示在 GUI 上,读取下一行并更新标签..等等,直到我到达文件的末尾。 (实际上并没有读取传感器值,它只是创建了一个虚拟函数。相反,我正在从 .txt 文件中读取数据)
我不知道该怎么做。任何反馈都会有所帮助。
class HealthWindow(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.configure(background='gray') # change bg color
label = Label(self, text="Health Status", bg="gray", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = ttk.Button(self, text="Back to Main",
command=lambda: controller.show_frame(FirstWindow))
# ttk buttons are better looking
button1.pack()
displayline = Label(self, text="", font=LARGE_FONT)
displayline.pack()
def readSensor():
with open("data.txt") as f:
#for line in f:
#time.sleep(2)
temp = f.readline()
displayline.configure(text=str(temp))
def update():
readSensor()
self.after(1000, update)
buttonClick = ttk.Button(self, text="View Status", command= lambda:
readSensor()) # ttk buttons are better looking
buttonClick.pack()
【问题讨论】:
-
如果你总是打开文件,那么你将总是只读第一行。您只需打开文件一次,并在阅读
readSensor()中的行时保持打开状态@ -
顺便说一句:你必须在另一个函数中创建函数吗?你不能在课堂上创建普通方法 - 使用
self吗? -
你从来没有打电话给
update,所以你期望什么?每次调用update时打开文件也是恶意的。 -
你可以使用
command=readSensor- 没有()
标签: python python-3.x user-interface tkinter