【发布时间】:2018-03-10 12:21:38
【问题描述】:
我正在尝试通过子类化 Frame 来制作自定义 Tkinter 小部件,以制作包含项目的可滚动小部件。我有 2 个窗口,我的根窗口和一个顶层窗口,我需要我的自定义小部件来打包到顶层窗口。
我的问题是,尽管将“顶部”作为我的自定义小部件的父级,它仍然打包在根窗口中。我已经尝试过其他小部件,它们可以很好地打包到顶层窗口。
我的代码:
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 级别,以便更直接地看出哪个窗口是哪个窗口。
【问题讨论】:
-
@Nae 我不确定你的意思。为了清楚起见,上面的代码是我实际程序的一个非常精简的版本。上面的代码本身确实会产生一个 GUI。
-
我的错,错过了
mainloop。