Montague27 Montague27 - 3 months ago 11
Python Question

Python can't add canvas to ttk notebook page

from tkinter import *
from tkinter import ttk

class MainGame(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()

def initUI(self):
global canvas
# ===Part A ===
self.parent.title('PythonPage')
self.pack(fill = BOTH, expand = 1)
self.page = ttk.Notebook(self, width = 650 ,height = 630)
self.page1 = ttk.Frame(self)
self.page.add(self.page1, text = 'Tab1')
self.page.pack(expand = 1, anchor = 'nw', side = 'top')
# ===Part B ===
canvas = Canvas(self)
canvas.create_rectangle([10,10, 650,630], fill = 'blue')
canvas.pack(fill = BOTH, expand = 1)
canvas.update()
self.a = Label(self, text = 'Haha')
self.a.place(x=50,y=50)

root = Tk()
root.geometry('925x650')
main = MainGame(root)
root.mainloop()


How can I add my rectangle into ttk's notebook? I found that my rectangle is always created below the notebook, but this situation is not the same with
Label
.

I want to put the rectangle inside the notebook, should I add something to
self.page1
?.

Answer

If you want the canvas to be in the notebook, you must add it to one of the notebook pages. For example, if you want it in self.page, you would change this line:

canvas = Canvas(self)

... to this:

canvas = Canvas(self.page1)