How to update label on tkinter

偶尔善良 提交于 2021-02-13 17:42:10

问题


I would like to update a label once I press one of the buttons. Here is my code - I added a label (caled label1), now I have two issues:

  1. It presents some gibberish
  2. How do I update the label with text right when the user is pressing the Browse button?
from tkinter import *
import threading

class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def init_window(self):
        self.var = IntVar()
        self.master.title("GUI")
        self.pack(fill=BOTH, expand=1)
        quitButton = Button(self, text="Exit", command=self.client_exit)
        startButton = Button(self, text="Browse", command=self.start_Button)
        label1 = Label(self, text=self.lable_1)

        quitButton.grid(row=0, column=0)
        startButton.grid(row=0, column=2)
        label1.grid(row=1, column=0)

    def client_exit(self):
        exit()

    def lable_1(self):
        print('starting')

    def start_Button(self):
        def f():
            print('Program is starting')
        t = threading.Thread(target=f)
        t.start()

root = Tk()
root.geometry("250x50")
app = Window(root)
root.title("My Program")
root.mainloop()

回答1:


Use self.label['text'] to change text

(Minimal?) Working example:

import tkinter as tk

class Window(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)

        # tk.Frame.__init__ creates self.master so you don't have to
        #self.master = master 

        self.init_window()

    def init_window(self):
        self.pack(fill=tk.BOTH, expand=1)

        quit_button = tk.Button(self, text="Exit", command=root.destroy)
        start_button = tk.Button(self, text="Browse", command=self.on_click)

        self.label = tk.Label(self, text="Hello")

        quit_button.grid(row=0, column=0)
        start_button.grid(row=0, column=1)

        self.label.grid(row=1, column=0, columnspan=2)

    def on_click(self):
        self.label['text'] = "Starting..."

root = tk.Tk()
app = Window(root)
root.mainloop()


来源:https://stackoverflow.com/questions/40472604/how-to-update-label-on-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!