[Tutor] Tkinter canvas on frame
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Feb 28 05:03:06 EST 2022
On 28/02/2022 06:30, Phil wrote:
> class Root(tk.Tk):
> def __init__(self):
> super().__init__()
> self.title("Canvas Template")
> self.geometry("400x300")
>
> self.frame = tk.Frame(background='cornflowerblue')
You need a parent for the frame, which should be self.
> self.frame.pack(fill=tk.BOTH, expand=1)
> self.frame.pack_propagate(0)
>
> canvas = tk.Canvas(self, relief='flat', background='lightgrey',
> width=200, height=200)
And the parent of the canvas is the frame not self. This is why the
canvas is on top of the frame.
By making it a fixed size it will look weird when you resize the window.
Its the layout managers job to control size and position inside the
window. Just let it do its job.
> canvas.pack(anchor='center', padx=10, pady=10)
>
> quit_button = tk.Button(self, text="Quit", command=self.quit)
> quit_button.pack(side=tk.BOTTOM, anchor='se', padx=10, pady=10)
I did this and it seemed to work.
import tkinter as tk
class Root(tk.Tk):
def __init__(self):
super().__init__()
self.title("Canvas Template")
self.frame = tk.Frame(self, background='cornflowerblue')
self.frame.pack(side='top', fill='both', expand=True)
canvas = tk.Canvas(self.frame, relief='flat',
background='lightgrey')
canvas.pack(side='top',anchor='center', fill='both',
expand=True, padx=10, pady=10)
self.quit_button = tk.Button(self, text="Quit", command=self.quit)
self.quit_button.pack(side=tk.BOTTOM, anchor='se', padx = 10,
pady=10)
r = Root()
r.mainloop()
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list