Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter command for button not working [duplicate]

Tags:

python

tkinter

I'm trying to make my program change the text based on a variable selected in the dropdown menu, but the button to activate the command doesn't seem to be working. From what I can see, the select function run's once the program is loaded and then never again, regardless of when I click the button.

from Tkinter import *

class App:

    def __init__(self, root):
        self.title = Label(root, text="Choose a food: ",
                           justify = LEFT, padx = 20).pack()
        self.label = Label(root, text = "Please select a food.")
        self.label.pack()

        self.var = StringVar()
        self.var.set("Apple")
        food = ["Apple", "Banana", "Pear"]
        option = apply(OptionMenu, (root, self.var) + tuple(food))
        option.pack()

        button = Button(root, text = "Choose", command=self.select())
        button.pack()

    def select(self):
        selection = "You selected the food: " + self.var.get()
        print(self.var.get()) #debug message
        self.label.config(text = selection)

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    root.mainloop()

I'm a beginner on Tkinter, and I'm trying to figure out the basics before I go into making my full app. Thanks in advance :)

like image 471
Rikg09 Avatar asked Jan 19 '26 18:01

Rikg09


1 Answers

Try changing

button = Button(root, text = "Choose", command=self.select())

into

button = Button(root, text = "Choose", command=self.select)

Note the removed parentheses after self.select. This way, the method only gets referenced and not actually executed until you press the button.

like image 109
Noshii Avatar answered Jan 22 '26 07:01

Noshii