简体   繁体   中英

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). It's time I clean it up, and I'm having problems making tkinter work in my classes.

Here is a simplified example. It is only attempting to place a ttk.Entry widget into the class, which is inheriting from 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.

Also, I think you can get rid of self.frame . Set self as the parent for the widgets in MyClass instead of self.frame .

Please Don't use the GRID method in Tkinter. It's the worst method in Tkinter. Please use the Place() method to design your GUI. It's very easy to implement.

For more check details over Place() refer to this post how to i position buttons in tkinter?

The place method is not complex like grid(). Check the post to make your GUI better in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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