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

前端 未结 2 1973
后悔当初
后悔当初 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 04:04

    Most times, callbacks drop the return value (all tkinter callbacks do), if any. This is because is is a bit awkward to manage return values using the observer pattern which is most often used for callbacks.

    There are two main ways to transfer a value from the CB to where it is needed:

    One is to use a container object - that may be a simple python list or dict, or a more elaborate data class that is accessible by the callback, and mutated to assign the proper values to it.

    here is a very simple example using a dictionary:

    import tkinter as tk 
    
    def print_info():
        print(f'from print_info: {information_transfer}')
    
    def submit(): 
        information_transfer['name'] = name_entry.get() 
        print(f'after input: {information_transfer}')
           
    root=tk.Tk()   
    root.geometry("600x400") 
       
    name_label = tk.Label(root, text = 'Username', font=('calibre', 10, 'bold')) 
    name_entry = tk.Entry(root, font=('calibre', 10, 'normal')) 
         
    sub_btn = tk.Button(root,text='Submit', command=submit)
    info_btn = tk.Button(root,text='print info', command=print_info)
    
    
    name_label.grid(row=0, column=0) 
    name_entry.grid(row=0, column=1)  
    sub_btn.grid(row=2, column=1) 
    info_btn.grid(row=3, column=1) 
    
    information_transfer = {'name': None, 'other': None}
    print(f'before input: {information_transfer}')
    
    root.mainloop()
    

    Another is the OOP approach described by @DavidGildour in another answer.

提交回复
热议问题