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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With