How do you create a Button on a Tkinter Canvas?

TkinterPythonGUI-Programming

Canvas widget is one of the versatile widgets in the Tkinter library. You can use canvas to draw different shapes, arcs, and objects to animate within the canvas. To create a button on a Tkinter Canvas, simply pass the parent as the canvas in place of a parent in the Button constructor.

Example

In this example, we will see how to create a Button inside a canvas widget.

#Import the required libraries
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of Tkinter Frame
win.geometry("700x350")

#Define a function for exit
def exit_program():
   win.destroy()


#Add a canvas widget
canvas = Canvas(win, width= 350)

#Add a Label widget in the Canvas
label = Label(canvas, text= "Click the Button to Exit", font= ('Helvetica 17 bold'))
label.pack(pady= 30)

#Create a button in canvas widget
ttk.Button(canvas, text= "Exit", command= exit_program).pack()
canvas.pack()

win.mainloop()

Output

Running the above code will display a window with a button inside the canvas.

Clicking the button "Exit" will close the window.

raja
Published on 25-May-2021 09:40:43
Advertisements