python - 在 Canvas 中创建框架

标签 python tkinter

我正在尝试使框架可滚动,而我发现这样做的唯一方法是制作可滚动的 Canvas 并向其添加框架。如果对我有用,这会很好用。

我能够创建一个工作正常的可滚动 Canvas ,但我似乎无法在其中正确添加框架:

    self.title = Label(root, text="Brnr", font=("Helvetica", 50), anchor = W, pady = 40, padx = 50)
    self.title.pack (anchor = NW)
    #creates title widget for title

    self.frame = Frame(screen, bd =1)
    self.frame.pack(fill = BOTH)
    #Creates frame widget under which all other widgets will be kept

    self.canvas = Canvas(self.frame,  bd=1,scrollregion=(0,0, 1000, 1000), height = 600)
    #creates canvas so that screen can be scrollable

    self.scrollbar = Scrollbar(self.frame, command=self.canvas.yview)
    #creates scrollbar

    self.canvas.config(yscrollcommand=self.scrollbar.set)  
    #connects the scrollbar to the canvas

    self.scrollbar.pack(side=RIGHT, fill=Y)                     
    self.canvas.pack(expand=YES, fill=BOTH) 
    #packs the scrollbar and canvas so that they fill the remainder of the screen


    self.frameC = Frame(bg = "red")
    self.canvas.create_window(0,0, anchor = NW, window = self.frameC, width = 200, height = 200)
    #creates window on the scrollable area to add other widgets

    self.frameC.pack()
    self.groupRec = LabelFrame(self.frameC, text ="Recommendations:", font=("Helvetica", 20))
    self.groupRec.pack()
    self.signupButton = Button(self.groupRec, text="Sign Up", width=10)
    self.signupButton.pack(side=RIGHT)
    #creates button to submit login

这给了我一个可滚动但空的 Canvas ,没有任何标签框/按钮出现。

最佳答案

默认情况下,当您将窗口添加到 Canvas 时,窗口的中心将位于您提供的坐标处。因此,框架的中心将位于 0,0,即 Canvas 的左上角。您看不到小部件,因为它们在 Canvas 的边界之外。

解决方案是包括anchor="nw"在调用 create_window ,这会将框架的左上角放在 Canvas 的左上角。

不要忘记设置 Canvas 的滚动区域以匹配框架的大小。最简单的方法是使用命令 self.canvas.config(scrollregion=self.canvas.bbox("all")) .您可能还需要将绑定(bind)添加到 <Configure>在 Canvas 上,以便您可以在用户调整窗口大小时调整内部框架的大小。这并不总是必要的,这在一定程度上取决于您要完成的目标。

这里有一个专业提示:要调试此类问题,临时为您的框架和 Canvas 提供不同的颜色以更轻松地可视化正在发生的事情确实很有帮助。

关于python - 在 Canvas 中创建框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6100748/

相关文章:

python - 使用 Tkinter 显示一系列 PIL 图像

tkinter - 如何为 Tk 构建包装器?

python - 在python进程之间共享tkinter窗口对象

python - 保存新文件时 IDLE 卡住/无响应

python - 使用多个模块 Python

python - 如何重复数据帧的某些行?

python - pyPandas 功能请求 : reverse/negative df. 下降

python-2.7 - 如何并排使用 Tkinter 和 Socket

python - SimpleJson 处理相同的命名实体

python - 是否有一个相当于 PyXll `@xl_func(macro=True)` 和 xlwings 的装饰器?