How to create a Button on a Tkinter Canvas?



Canvas provides direct control over the drawing of individual pixels and helps to combine them all to make a visualization. With the Tkinter Canvas widget, we can create images, draw shapes, and even, we can animate objects in an application.

In order to define a button widget, we have to provide the parent window or frame object to a button so that it ensures where it should have to be displayed. By passing the canvas object to the Tkinter Button, we can create buttons in the canvas too.

Example

#Import the required Libraries
from tkinter import *
from tkinter import ttk
import random

#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of Tkinter frame
win.geometry("750x250")

def change_style():
   label.config(font=('Impact', 15 ,'italic'), foreground= "white", background="black")
   button.config(text= "Close", command=lambda:win.destroy())

#Create a Canvas
canvas= Canvas(win, width= 600, height=200, bg='bisque')
canvas.pack(fill= BOTH, expand= True)

#Create a Label
label=Label(canvas, text= "Welcome to TutorialsPoint.com", font=(None, 15))
label.pack(pady=14)
#Create a button in canvas
button= Button(canvas, text="Click Me", command= change_style)
button.pack(pady=20)

win.mainloop()

Output

Executing the above code will display a canvas with a button and a Label Text in it.

Now, click the button "Click Me" to change the style of the label Text.


Advertisements