简体   繁体   English

为什么不能使用tkinter网格方法放置此类?

[英]Why can't I place this class using the tkinter grid method?

I have an existing Python 3 program which I wrote quick-and-dirty without any object-oriented techniques (it was my first Python program). 我有一个现有的Python 3程序,无需任何面向对象的技术就可以快速编写代码(这是我的第一个Python程序)。 It's time I clean it up, and I'm having problems making tkinter work in my classes. 现在该清理一下了,在使tkinter在我的课堂上工作时遇到了问题。

Here is a simplified example. 这是一个简化的示例。 It is only attempting to place a ttk.Entry widget into the class, which is inheriting from ttk.Frame: 它只是试图将ttk.Entry小部件放置到继承自ttk.Frame的类中:

import tkinter as tk
from tkinter import ttk

class MyClass(ttk.Frame):
    def __init__(self, parent):
        self.frame = ttk.Frame(parent)

        # Entry widget
        self.entValue = ttk.Entry(self.frame)
        self.entValue.grid(column=0, row=0)

# tkinter init
root = tk.Tk()

# Make the class instance and place it
test = MyClass(root)
test.grid(column=0, row=0)

It gives me the following error: 它给了我以下错误:

Traceback (most recent call last):
  File "{path_to_code}/so.py", line 17, in <module>
    test.grid(column=0, row=0)
  File "{path_to_python}\Python35-32\lib\tkinter\__init__.py", line 2072, in grid_configure
    self.tk.call(
AttributeError: 'MyClass' object has no attribute 'tk'

What am I missing? 我想念什么?

Your Frame hasn't been initialized. 您的相框尚未初始化。 Add super().__init__(parent) to the top of your MyClass.__init__ method to allow ttk to initialize the frame. MyClass.__init__方法的顶部添加super().__init__(parent) ,以允许ttk初始化框架。

Also, I think you can get rid of self.frame . 另外,我认为您可以摆脱self.frame Set self as the parent for the widgets in MyClass instead of self.frame . self设置为MyClass的小部件的父级,而不是self.frame

Please Don't use the GRID method in Tkinter. 请不要在Tkinter中使用GRID方法。 It's the worst method in Tkinter. 这是Tkinter中最糟糕的方法。 Please use the Place() method to design your GUI. 请使用Place()方法来设计您的GUI。 It's very easy to implement. 这很容易实现。

For more check details over Place() refer to this post how to i position buttons in tkinter? 有关Place()的更多检查详细信息,请参阅此文章如何在tkinter中放置按钮?

The place method is not complex like grid(). place方法并不像grid()那样复杂。 Check the post to make your GUI better in Python. 检查文章以使您的GUI更好地使用Python。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM