【问题标题】:Tkinter: Placing a widget in a frame actually places it in rootTkinter:将小部件放置在框架中实际上将其放置在根目录中
【发布时间】:2020-09-24 22:05:45
【问题描述】:

所以我在 Windows (python 3.8.5) 和 Linux (python 3.8.2) 上出现了一个独特的问题。当我将一个小部件放置在某个 Frame 中时,无论出于何种原因,它实际上都会放置在 Root 中。

我正在使用TkinterExtensions 库。我看过这个Answer,但没有帮助。无论我做什么,我都会遇到问题,但仅限于一帧。我现在怀疑这可能是 Tkinter 库错误。

编辑:它似乎只发生在 python 3.8.x 中。我在另一台装有 3.7.x 的电脑上试了一下,它按预期工作。

下面是一个非常通用的例子。

from TkinterExtensions import *

class Root(tk.Tk):
    # sets up Tkinter and creates the other windows and places them accordingly.
    def __init__(self):
        super().__init__()
        self.w1 = Window1(root=self).place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0)
        self.w2 = Window2(root=self).place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0)
        self.w3 = Window3(root=self).place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0)
        
        self.w1.hide()
        self.w2.hide()
        self.w3.hide()

class Window1(TkinterFrame):
    # ... anything needed for this frame
    # This is the frame that's causing the issue.
    # Despite the same code on all three windows, 
    # this one puts any widgets into root instead of as a child of this frame.
    
    def __init__(self, root)
        super().__init__(root)
        self.button = TkinterButton(master=self, Text="button").place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0)
    
class Window2(TkinterFrame):
    # ... anything needed for this frame
    # this frame works fine
    
class Window3(TkinterFrame):
    # ... anything needed for this frame
    # this frame works fine
    

如果需要,我可以使用更广泛的通用代码创建一个存储库。

另外,我是TkinterExtensions 库的作者。

【问题讨论】:

  • 我们不需要存储库,但我们需要minimal reproducible example
  • 您的意思是在Window1 中创建的按钮是放在根目录下的吗?你怎么知道它是放在根目录下的?此外,您的通用示例有一个非常流行的错误:使用place() 创建链小部件,例如self.button = TkinterButton(...).place(...),这使得self.button 成为None。您是否也通过将所有小部件从 TkinterExtensions 更改为普通的 tkinter 小部件来测试相同的示例,并查看是否出现相同的问题?
  • @acw1668 TkinterExtensions 库通过返回 self 解决了这个问题,所以不是真的。是的,我也把它们都改回来了。
  • 这似乎只发生在 python 3.8.x 中。我在另一台装有 3.7.x 的电脑上试了一下,它按预期工作。
  • 我尝试了您的通用示例(在修复了一些语法错误并添加了所需的代码以使其可运行之后),它适用于我在 Windows 7 中的 Python 3.8.5。Here 是代码。跨度>

标签: python python-3.x tkinter tkinter-layout


【解决方案1】:

在这个特定的框架中,我定义了 len 方法。一旦重命名它,布局管理器以及放置在其中的任何小部件都会按预期工作。 Tkinter.Frame 类没有定义 len 所以我不知道为什么它会导致问题,但确实如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    相关资源
    最近更新 更多