[英]Custom Tkinter Widget Won't Pack in Toplevel?
我正在尝试通过将Frame子类化以制作包含项目的可滚动小部件来制作自定义Tkinter小部件。 我有2个窗口,我的根窗口和一个顶层窗口,我需要自定义窗口小部件打包到顶层窗口。
我的问题是,尽管将“ top”设为自定义小部件的父级,但它仍打包在根窗口中。 我试过其他小部件,它们可以打包到顶级窗口中。
我的代码:
from tkinter import *
root = Tk()
root.config(bg="#000000")
root.wm_attributes("-alpha","0.7")
top = Toplevel()
top.config(bg="#000001")
top.wm_attributes("-topmost",1)
top.wm_attributes("-transparentcolor","#000001")
top.wm_title("TOPLEVEL")
class Scrollygrid(Frame):
def __init__(self, parent, columns, h, w):
super(Scrollygrid, self).__init__()
self.scrollbar = Scrollbar(self)
self.scrollbar.pack(side = RIGHT, fill = Y)
self.area = Canvas(self, yscrollcommand=self.scrollbar.set, width = w, height = h, bg = "#000001", bd = 0, highlightthickness = 0)
self.gridframe = Frame(height = h*10, width = w, bg = "#FF0000")
self.gridframe.pack_propagate(0)
self.area.create_window((0, 0), window = self.gridframe)
for i in range(500):
Label(self.gridframe, text = i).pack()
self.area.pack()
self.area.config(scrollregion = (self.area.bbox("all")))
self.scrollbar.config(command = self.area.yview)
def onScroll(event):
self.area.yview_scroll(int(-1*(event.delta/60)), "units")
self.area.bind_all("<MouseWheel>", onScroll)
self.scrollbar.pack_forget() #scroll wheel still works!
testgrid = Scrollygrid(top, 1,root.winfo_screenheight()-80,root.winfo_screenwidth()-(root.winfo_screenwidth()/10))
testgrid.pack(side = RIGHT, anchor = CENTER)
root.mainloop()
保留了透明的颜色和Alpha级别,以使您立即更清楚地看到哪个窗口。
top
不是您的自定义小部件的父级。 你永远不会过去。 您的Scrollygrid
正在传递parent
参数,仅此而已 。 没有任何东西告诉它甚至将其分配为父项作为属性。 因此,父级默认为Tk
实例root
。
更换:
super(Scrollygrid, self).__init__()
与:
super(Scrollygrid, self).__init__(parent)
为了通过给定的插件参数作为父超类, Frame
。 从根本上让Toplevel
, top
自定义类的父。 在这之后,您将得到进一步的错误,但已正确分配了父级。 验证方式:
print(repr(self.winfo_toplevel()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.