Rikg09 Rikg09 - 1 year ago 81
Python Question

Tkinter command for button not working

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.var = StringVar()
food = ["Apple", "Banana", "Pear"]
option = apply(OptionMenu, (root, self.var) + tuple(food))

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

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)

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 :)

Answer Source

Try changing button = Button(root, text = "Choose", command=self.select()) to 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download