Tkinter Button is an widget used to add buttons in python applications. These buttons can perform different actions according to requirement . These buttons can display images instead of plain text.
Tkinter also allows us to format these buttons accordingly (using colors , fonts) . Each button has a specific function , which calls automatically when button is clicked . Adding button into python application is very easy task .
Button( MainWindow , OtherParameters..... )
- MainWindow : The main window is a master window , in which all the widgets are placed. We can say it is a container , that holds all the content of the application.
- OtherParameters : We can add multiple parameters to an button. Parameters are the additional information or characteristics that we can add to a function . We can add button’s color , background-color , height etc. Also , we can pass an action ( which function performs on click ) as an parameter.
Example 1 – A simple button
from tkinter import * win = Tk() btn = Button(win , text = "Button" , command = quit) btn.pack() win.mainloop()
- In the above code , we have create an main window in line 2
- line 3 is responsible for creating button , in this we have use Button() widget of tkinter
- Here we pass 3 parameters to button ,first is main window. Second one is text to be display on button.
- Third parameter pack() organizes the widgets in blocks.
- The last line is actual responsive to display output on the screen.
If you want to learn more about pack() than you can visit the link blow:
Example 2 – Tkinter Button using OOP
from tkinter import * from tkinter import messagebox class mybutton: def __init__(self, masterWindow): frame = Frame(masterWindow) frame.pack() self.button = Button(frame, text = "Exit" , bg= 'red',fg = 'white',command= quit,pady=5, padx=20, highlightcolor='gray') self.button.pack(side=LEFT) self.Click = Button(frame , bg = 'green', command=self.btn_action, text="Click me",font='arial') self.Click.pack(side=RIGHT) def btn_action(self): print("Button Clicked!!!") messagebox.showinfo("Greetings","Thanks for click on the button") root = Tk() obj = mybutton(root) root.mainloop()
In code above , there are two buttons:
- Exit : It uses built in quit command and closes window when clicked .
- Click Me : It returns an pop-up messagebox with some text and OK button . Also it prints “Button Clicked” into console. For this we have created function , btn_function() within class mybutton .
So , this is all about creating button with some action in Tkinter . I hope you guys enjoyed the article !! Thanks!!!