我在tkinter中实现了自己的可滚动框架类:
class scrolledFrame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.canvas = tk.Canvas(self)
self.canvas.pack(fill = "both", expand = True, side = "left")
self.scroll = tk.Scrollbar(self, command = self.canvas.yview)
self.scroll.pack(side = "right", fill = "y")
self.canvas.config(yscrollcommand = self.scroll.set)
self.content = tk.Frame(self.canvas)
self.content.bind("<Configure>", self.resizeCanvas)
self.contentWindow = self.canvas.create_window((0,0), window = self.content, anchor = "nw")
self.content.bind("<Enter>", self.enableScrollCanvas)
self.content.bind("<Leave>", self.disableScrollCanvas)
def scrollCanvas(self, event):
self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")
def enableScrollCanvas(self, event):
self.canvas.bind_all("<MouseWheel>", self.scrollCanvas)
def disableScrollCanvas(self, event):
self.canvas.unbind_all("<MouseWheel>")
def resizeCanvas(self, event):
self.update_idletasks()
self.canvas.config(scrollregion = self.canvas.bbox("all"))
self.canvas.itemconfig(self.contentWindow, width = self.canvas.winfo_width())
root = tk.Tk()
exampleFrame = scrolledFrame(root)
exampleFrame.pack()
exampleLabel = tk.Label(exampleFrame.content, text = "I'm in the scrolled frame!")
exampleLabel.pack()
root.mainloop()
这很好,但问题是要将小部件添加到滚动框中,父对象必须是exampleFrame.content
。我看过其他几个例子,它们都有相同的局限性。是否可以将类配置为exampleFrame
可以作为小部件的父级而不是exampleFrame.content
?提前谢谢
感谢@Novel帮助回答这个问题。
通过向类中添加
__getattr__
方法,可以实现所需的行为。如果类从tk.Frame
继承,因此该类已被删除,那么这将不起作用。代码如下:如果你不介意一些小把戏,你可以模拟你想要的。不过这有点像黑客
诀窍在于,当您调用
tk.Frame.__init__
时,需要将画布作为父对象,使self
成为内容框架。当然,要做到这一点,您必须首先创建画布,要创建画布,您必须创建外部框架它看起来像这样:
但是,当您执行上述操作并尝试在
scrolledFrame
的实例上调用pack
、place
或grid
时,它将执行错误的操作,因为该实例指向内部框架而不是外部框架这里有一个技巧:解决方案是将调用重定向到
pack
、place
和grid
到外部框架有了它,您可以随意使用
scrolledFrame
,只要在将它添加到布局时使用pack
、place
或grid
这是一个完整的工作示例,不过为了简洁起见,我删除了mouseweel代码
相关问题 更多 >
编程相关推荐