Adding a button widget
The button can be created using the Button class. The Button class constructor requires a reference to the main window and to the options.
Syntax:
Button(window, attributes)
You can set the following important properties to customize a button:
text : caption of the button
bg : background colour
fg : foreground colour
font : font name and size
image : to be displayed instead of text
command : function to be called when clicked
from tkinter import * window=Tk() btn=Button(window, text="This is Button widget", fg='blue') btn.place(x=80, y=100) window.title('Hello Python') window.geometry("300x200+10+10") window.mainloop()
Output:
Multiple Buttons with different
text color,
background colors,
different locations,
Fonts
from tkinter import * window=Tk() btn1=Button(window, text="Button one", fg='blue',bg='red',font=("Arial Bold", 15)) btn2=Button(window, text="Button two", fg='blue',bg='green',font=("Arial Bold", 15)) btn3=Button(window, text="Button three", fg='white',bg='blue',font=("Arial Bold", 15)) btn4=Button(window, text="Button four", fg='blue',bg='pink', font=("Arial Bold", 15)) btn1.place(x=10, y=100) btn2.place(x=180, y=100) btn3.place(x=10, y=300) btn4.place(x=180, y=300) window.title('Hello Python') window.geometry("500x400+10+10") window.mainloop()
Output:
Handle button click event
We want to display a message in lable as a button is clicked.
First, we will write the function that we need to execute when the button is clicked:
def clicked():
lbl.configure(text=”Button was clicked !!”)
Then we will wire it with the button by specifying the function like this:
btn = Button(window, text=”Click Me”, command=clicked)
Note that, we typed clicked only not clicked() with parentheses.
Now the full code will be like this:
from tkinter import * window = Tk() window.title("Welcome to Button Event Handling") window.geometry('350x300') window.configure(bg='blue') lbl = Label(window, text="Hello",font=("Arial Bold", 20)) #lbl.grid(column=0, row=0) lbl.place(x=10,y=40) def clicked(): lbl.configure(text="Button was clicked !!") btn = Button(window, text="Click Me", command=clicked) #btn.grid(column=1, row=0) btn.place(x=10,y=200) window.mainloop()
Output:
On clicking Button