[Tutor] Tkinter canvas on frame

Phil phillor9 at gmail.com
Mon Feb 28 01:30:59 EST 2022


On 28/2/22 11:22, Alan Gauld via Tutor wrote:

>>>> from tkinter import *
>>>> top = Tk()
>>>> f = Frame(top,background="blue")
>>>> f.pack(expand=True)
>>>> b = Button(f, text='Hello World')
>>>> b.pack(anchor='center', padx=10,pady=10)
> Is that what you mean?

I've modified Alan's code slightly so that it looks more like my own and 
it works perfectly.

import tkinter as tk

top = tk.Tk()
f = tk.Frame(top,background="blue", width = 400, height = 300)
f.pack(fill=tk.BOTH, expand=1)
f.pack_propagate(0)

c = tk.Canvas(f, width = 100, height = 100)
b = tk.Button(f, text='Hello World')

c.pack(anchor='center', padx=10, pady=10)

b.pack(side=tk.BOTTOM, anchor='se', padx=10,pady=10)

As far as I can see the following is substantially the same code except 
that I'm using a class and it displays the blue frame only above the 
canvas. I've played with this for hours and I cannot see why one works 
and the other doesn't.

import tkinter as tk


class Root(tk.Tk):
     def __init__(self):
         super().__init__()
         self.title("Canvas Template")
         self.geometry("400x300")

         self.frame = tk.Frame(background='cornflowerblue')
         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)

         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)

-- 

Regards,
Phil



More information about the Tutor mailing list