How to create a button on tkinter canvas?

I created a frame and then a canvas.
What I want to do next is add a button on the canvas. However, when I packaged Button, I do not see Canvas!

Here is what I tried:

from Tkinter import Tk, Canvas, Frame, Button from Tkinter import BOTH, W, NW, SUNKEN, TOP, X, FLAT, LEFT class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Layout Test") self.config(bg = '#F0F0F0') self.pack(fill = BOTH, expand = 1) #create canvas canvas1 = Canvas(self, relief = FLAT, background = "#D2D2D2", width = 180, height = 500) canvas1.pack(side = TOP, anchor = NW, padx = 10, pady = 10) #add quit button button1 = Button(canvas1, text = "Quit", command = self.quit, anchor = W) button1.configure(width = 10, activebackground = "#33B5E5", relief = FLAT) button1.pack(side = TOP) def main(): root = Tk() root.geometry('800x600+10+50') app = Example(root) app.mainloop() if __name__ == '__main__': main() 
+5
source share
2 answers

The Tkinter pack manager tries to resize the parent widget to the correct size to contain the child widgets, and by default no more. Thus, the canvas is there, but it is exactly the same size as the button, and thus invisible.

If you want to place the widget on the canvas without causing the canvas to dynamically resize, you need the Canvas.create_window() function:

 # ... snip ... button1 = Button(self, text = "Quit", command = self.quit, anchor = W) button1.configure(width = 10, activebackground = "#33B5E5", relief = FLAT) button1_window = canvas1.create_window(10, 10, anchor=NW, window=button1) 

This will create your button with the upper left corner at (10, 10) relative to the canvas, without resizing the canvas itself.

Note that you can replace the window argument with a link to any other Tkinter widget. However, one caveat: the named widget must be a child of the top-level window containing the canvas, or a child of any widget located in the same top window.

+11
source

you can use the geometry manager button1.place (x = 0, y = 0) instead of the package (side = TOP) pack resizes the main widget to make it large enough to hold the child widget

http://effbot.org/tkinterbook/pack.htm#Tkinter.Pack.pack_propagate-method

http://effbot.org/tkinterbook/place.htm

+2
source

Source: https://habr.com/ru/post/955941/


All Articles