python tkinter return value from function used in command

前端 未结 5 472
遇见更好的自我
遇见更好的自我 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:31

    it's easy just declare A a global.

    def button:
    global A
    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 = button).grid(row = 1, column = 1)
    # and then A is not empty
    B= A
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-16 01:42

    Short answer: you cannot. Callbacks can't return anything because there's nowhere to return it to -- except the event loop, which doesn't do anything with return values.

    In an event based application, what you typically will do is set an attribute on a class. Or, if you're a beginner, you can set a global variable. Using a global variable isn't a good idea for real code that has to be maintained over time but it's OK for experimentation.

    So, for example, since C appears to be a global variable in your example, you would do something like:

    def button():
        global C
        mylabel = Label(myGui, text = "hi").grid(row = 0, column = 0)
        A = B.get()
        C = A
    
    0 讨论(0)
  • 2020-12-16 01:45

    You could call C.set from within the button function:

    def button:
        mylabel = Label(myGui, text = "hi").grid(row = 0, column = 0)
        A = B.get()
        C.set(A)
        # return A   # return values are useless here
    
    0 讨论(0)
  • 2020-12-16 01:47

    You create a child class of Tkinter.Tk, and define a member variable self.A in that class. Then you can mimic return behavior by

    self.A = B.get()
    

    See, Return values of Tkinter text entry, close GUI

    0 讨论(0)
提交回复
热议问题