I am experimenting with Tkinter for the first time, and am trying to call a function when a button is clicked. This is part of my code. mt is referring to a label that I have made dynamic by attaching it to a label so that I can change what the label says. I want the user to be able to type in something into an entry box, hit the button, and the it will change the label to what was typed.
def new(self):mt.set("New")e1 = Entry(master)e1.pack()def new_ok(self):mt.set("OK")#the next part is what I need help withif (checks if button has been clicked) button has been clicked:mt.set("#what it says in the entry box#")
How should I do this? I have looked on tutorials and read them but none of them have clearly acknowledged how to check if a button has been pressed and to respond.
If the question is: "How do you update a Label widget?"
then the answer is with the widget's configure
method.
# Tkinter in Python 2.7 & tkinter in 3.2
import Tkinter as tkclass GUI(tk.Tk):def __init__(self):tk.Tk.__init__(self)bF = tk.Frame(self, bd=8, relief='sunken')bF.pack(expand='true', fill='x')changeButton = tk.Button(bF, text='Change', bd=4, fg='white',relief='groove', activebackground='green',command=self.change_label)changeButton.pack()self.entryLabel = tk.Label(self, text='Hello')self.entryLabel.pack()self.mEntry = tk.Entry(self, bd=4, relief='sunken')self.mEntry.pack()def change_label(self):data = self.mEntry.get()self.entryLabel.configure(text=data)gui = GUI()
gui.mainloop()
You will want to make your GUI a class like in this example;
that way you can use the self. prefix to refer to the widget made in another method.
In your example it looks like you might be saying 'mt' is a control variable.
The answer would still be to make a class, so that you can use the self. prefix.
The control variable likely isn't necessary unless you would want
the label to be updated as you changed the contents of the Entry widget:
import Tkinter as tkclass GUI(tk.Tk):def __init__(self):tk.Tk.__init__(self)bF = tk.Frame(self, bd=8, relief='sunken')bF.pack(expand='true', fill='x')var = tk.StringVar()var.set('Hello')entryLabel = tk.Label(self, textvariable=var)entryLabel.pack()mEntry = tk.Entry(self, bd=4, relief='sunken', textvariable=var)mEntry.pack()gui = GUI()
gui.mainloop()