【问题标题】:Update tkinter Label to display a text file, one line at a time on my python GUI更新 tkinter 标签以在我的 python GUI 上一次显示一个文本文件
【发布时间】: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


【解决方案1】:

您只需打开文件一次 - 即。在__init__ - 然后逐行读取。

class HealthWindow(Frame):

    def __init__(self, parent, controller):
        super().__init__(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)) 
        button1.pack()

        # with self. to have access in other methods
        self.displayline = Label(self, text="", font=LARGE_FONT)
        self.displayline.pack()

        buttonClick = ttk.Button(self, text="View Status", command=self.update)
        buttonClick.pack()

        # open only once
        self.f = open("data.txt")

    # method,not internal function
    def update(self):
        try:
            temp = self.f.readline()
            self.displayline["text"] = temp
            self.after(1000, self.update)
        except Exception as ex:
            print('Error:', ex)
            print('Probably end of file')
            self.f.close()

顺便说一句:当你第二次点击update时,你仍然需要检查文件是否没有打开。


编辑: 现在按钮运行start_update 检查文件是否已经打开。

我使用self.f = None 来控制它。

after 仍在运行 update,而不是 start_update

class HealthWindow(Frame):

    def __init__(self, parent, controller):
        super().__init__(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)) 
        button1.pack()

        self.displayline = Label(self, text="", font=LARGE_FONT)
        self.displayline.pack()

        buttonClick = ttk.Button(self, text="View Status", command=self.start_update)
        buttonClick.pack()

        self.f = None # to see if it is open when you click button next time

    def start_update(self):
        if self.f is None:
            # open only once
            self.f = open("data.txt")
            self.update()        

    def update(self):
        temp = self.f.readline()
        self.displayline["text"] = temp

        if temp: # there was text in file
            self.after(1000, self.update)
        else:
            print('Probably end of file')
            self.f.close()
            self.f = None # so you can open again

【讨论】:

  • 非常感谢您的帮助。我进行了更正,现在收到此错误: buttonClick = ttk.Button(self, text="View Status", command=self.start_update) AttributeError: 'HealthWindow' object has no attribute 'start_update'
  • 你的缩进是否正确?缩进在 Python 中非常重要。他们可以改变一切。请参阅答案中的缩进。
  • 我修复了我的缩进,这很有效!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 2021-09-01
  • 2013-03-12
相关资源
最近更新 更多