2

I was wondering how to put a button inside of a canvas using the tkinter module. This question was asked, but it was 5 years ago and for a different version so It was not very convenient for my situation and I am still a beginner so I only understood about 3/4 of the code in the best answer. Here is the question: How to make a Button using the tkinter Canvas widget?

from tkinter import *
root = Tk()
c=Canvas(root,width=200,height=150,bg='blue')
c.pack(side = 'top')

c.create_text(100,50,anchor='c',fill='orange',font='Times 28',text='List')

button = Button(root, text="Quit",command=root.destroy)
button.pack()

mainloop()

When I run this code it creates the button below my Canvas and not on the Canvas. I looked for help on https://docs.python.org/3.7/library/tkinter.html the guide for the IDE I am using. I could not find a way to put the button on the Canvas even though I may or may not have missed something. If this question is seen as not helpful or unnecessary I apologize and will close it immediately.

Version of Python: 3.7

Level: Beginner

Running Code on: IDLE 64-bit

OS: Windows 10

pErs0nZ
  • 129
  • 2
  • 10

2 Answers2

2

When you use pack() tkinter will place the button on it's master (root), and the area where the canvas is drawn is already occupied.

To place the button on the canvas you should use the function create_window() on the canvas:

from tkinter import *

root = Tk()
c = Canvas(root,width=200,height=150,bg='blue')
c.pack(side = 'top')

c.create_text(100, 50, anchor='c', fill='orange', font='Times 28', text='List')

button = Button(root, text="Quit", command=root.destroy)
canvas_widget = c.create_window(100, 100, window=button)

root.mainloop()
figbeam
  • 7,001
  • 2
  • 12
  • 18
0

delete button.pack()

try use the code below

button = Button(root, text="Quit", command=root.destroy)

c.create_window(10, 10, anchor=NW, window=button)

邱俊華
  • 1
  • 1