In this TKinter Tutorial we are going to learn creating TKinter Button, also we will learn how you can interact with buttons in tkinter and how you can add commands for the buttons.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
from tkinter import ttk import tkinter as tk class Window(tk.Tk): def __init__(self): super(Window, self).__init__() self.title("Buttons in TKinter") self.minsize(350,300) self.wm_iconbitmap("myicon.ico") self.label = ttk.Label(self, text = "TKinter Application") self.label.grid(column = 1, row = 0) self.button = ttk.Button(self, text = "Click Me", command = self.click_me) self.button.grid(column=0, row=0) def click_me(self): self.label.configure(text = "GeeksCoders - Text is Changed") self.label.configure(foreground = 'white', background = 'green') self.label.config(font=("Courier", 20)) self.button.configure(text = "Button Changed") window = Window() window.mainloop() |
Using this code we have created a label, also we have added the button in the grid layout.
1 2 |
self.label = ttk.Label(self, text = "TKinter Application") self.label.grid(column = 1, row = 0) |
In here we have created our button, you need to give text for the button and you can see that we have given command for the button and this command is connected with click_me() method.
1 2 |
self.button = ttk.Button(self, text = "Click Me", command = self.click_me) self.button.grid(column=0, row=0) |
This is the method that we have already connected in the command section, basically in here when a user clicks the button we are going to change the text of the label with the button text. and for that you can use configure() method with the respected widgets.
1 2 3 4 5 |
def click_me(self): self.label.configure(text = "GeeksCoders - Text is Changed") self.label.configure(foreground = 'white', background = 'green') self.label.config(font=("Courier", 20)) self.button.configure(text = "Button Changed") |
Run the complete code and click on the button, this will be the result.