Tkinter-如何在ttk.Notebook()中添加画布/帧
问题描述
在YouTube和Google上搜索了很多次后,我学会了如何在Canvas
中添加全屏滚动条。它看起来像this。但现在我想将此框架/画布添加到ttk.Notebook()
中作为选项卡,如test project所示。但当我键入book.add(main,text='Tab 1')
时,它显示错误_tkinter.TclError: can't add .!frame.!canvas.!frame as slave of .!notebook
。有人知道如何将画布显示为框架并将其作为选项卡添加到Notebook()中吗?
以下是主要代码:
from tkinter import *
from tkinter import ttk
root=Tk()
root.title('Scroll Bar Test')
root.geometry('500x400')
#Create Main Frame
main_frame=Frame(root)
main_frame.pack(fill=BOTH,expand=1)
#Create Canvas to add scrollbar
my_canvas=Canvas(main_frame)
my_canvas.pack(side=LEFT,fill=BOTH,expand=1)
#Create ScrollBar
my_scrollbar=ttk.Scrollbar(main_frame,orient=VERTICAL,command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT,fill=Y)
#Adding ScrollBar to Canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>',lambda e: my_canvas.configure(scrollregion=my_canvas.bbox("all")))
#Creating Frame to show the Canvas
main=Frame(my_canvas)
#Showing Canvas into/as a Frame
my_canvas.create_window((0,0),window=main,anchor="nw")
for i in range(100):
Button(main, text=f'Button {1+i} Yoo!',font='arial 15').pack()
#Create NoteBook
book=ttk.Notebook(root)
book.pack()
#
book.add(main,text='Tab 1')
root.mainloop()
解决方案
代码中有几个问题:
- 应在
book
中添加main_frame
(外框)而不是main
(内框) - 应在
main
绑定<Configure>
,而不是my_canvas
- 将
main_frame
创建为book
的子级,而不是root
以下是修改后的代码:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('Scroll Bar Test')
root.geometry('500x400')
# Create NoteBook
book = ttk.Notebook(root)
book.pack(fill=tk.BOTH, expand=1)
# Create Main Frame
main_frame = tk.Frame(book)
# put the main frame into notebook
book.add(main_frame, text='Tab 1')
# Create canvas inside main frame
my_canvas = tk.Canvas(main_frame)
my_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
# Create ScrollBar inside main frame
my_scrollbar = ttk.Scrollbar(main_frame, orient=tk.VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
my_canvas.configure(yscrollcommand=my_scrollbar.set)
# Creating internal frame for the buttons
main = tk.Frame(my_canvas)
main.bind('<Configure>', lambda e: my_canvas.configure(scrollregion=my_canvas.bbox("all")))
my_canvas.create_window((0,0), window=main, anchor="nw")
for i in range(100):
tk.Button(main, text=f'Button {1+i} Yoo!', font='arial 15').pack()
root.mainloop()
请注意,我已将from tkinter import *
更改为import tkinter as tk
,因为不建议使用通配符导入。
相关文章