How to return a value of a function given as a command in tkinter

前端 未结 2 1846
后悔当初
后悔当初 2021-01-27 03:39

I\'ve written a very simple code with python tkinter, it contains an input box. I\'d like to keep the value inserted by the user to myself, in case I need to use it

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-27 03:58

    I would recommend using OOP approach, to have an object retaining a state:

    import tkinter as tk
    
    
    class Program:
        def __init__(self):
            self.root = tk.Tk()
            self.name_label = tk.Label(self.root, text='Username',
                                       font=('calibre', 10, 'bold'))
            self.name_entry = tk.Entry(self.root, font=('calibre', 10, 'normal'))
            self.sub_btn = tk.Button(self.root, text='Submit', command=self.submit)
            self.submitted_var = tk.StringVar()
    
            self.submitted_label = tk.Label(self.root, text="Submitted name: ")
            self.submitted_entry = tk.Label(self.root, textvariable=self.submitted_var)
    
        def setup(self):
            self.submitted_label.grid(row=0, column=0)
            self.submitted_entry.grid(row=0, column=1)
            self.name_label.grid(row=1, column=0)
            self.name_entry.grid(row=1, column=1)
            self.sub_btn.grid(row=2, column=1)
    
        def submit(self):
            self.submitted_var.set(self.name_entry.get())
    
        def run(self):
            self.setup()
            self.root.mainloop()
    
    if __name__ == '__main__':
        Program().run()
    

    Then you can use self.submitted_var.get() anywhere to get the last submitted value. Although, the more straight-forward way would be to link a StringVar directly to name_entry, but then it would change every time the Entry widget value changes, rendering the submit button useless.

提交回复
热议问题