python tkinter return value from function used in command

前端 未结 5 474
遇见更好的自我
遇见更好的自我 2020-12-16 01:22

how do i get the return value A to C? I am not using class by the way.

def button:
    mylabel = Label(myGui, text = \"hi\").grid(row = 0, column = 0)
    A          


        
5条回答
  •  再見小時候
    2020-12-16 01:38

    Old question, but most answers suggested a global variable. I don't like using too many global variables in my projects, so here's my solution.

    When declaring your Tkinter button, you can use a lambda function as the command. This lambda can interact with variables that are within the same namespace as the button you are defining. Be sure to define this variable before initializing the button.

    def button():
        mylabel = Label(myGui, text = "hi").grid(row = 0, column = 0)
        A = B.get()
        return A
    
    B = StringVar()
    C = ""
    myentry = Entry(myGui, textvariable = B).grid(row = 1, column = 0)
    Submit = Button(myGui, text = "Submit", command = lambda: C=button()).grid(row = 1, column = 1)
    

    You may need to have self as an argument for button depending on your project organization, but the concept is the same. Lambda commands are also useful for passing arguments to the button command.

提交回复
热议问题