Skip to content Skip to sidebar Skip to footer

How To Call An Action When A Button Is Clicked In Tkinter

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 mad

Solution 1:

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.2import Tkinter as tk

classGUI(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()

    defchange_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 tk

class 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()

Solution 2:

I'm no Tkinter wiz, but one of the first things I see in the module docs for Tkinter is A Simple Hello World Program, which has the answer to your question in it. (As with most GUI toolkits, the answer is callback or event handler functions.) The member function say_hi is a callback for the Hello button.

Post a Comment for "How To Call An Action When A Button Is Clicked In Tkinter"