首页 > 解决方案 > Tkinter:“str”对象在尝试关闭时没有属性“children”

问题描述

我正在尝试在 python 3.7 中学习 tkinter gui,我有以下代码:

from tkinter import *
# Configuración de la ventana principal
root=Tk()
root.title("Cath Config")


#Definición de clases
#Frames
class marco(Frame):
    def __init__(self, master=None, color="#F3F3F3", ancho="1024", alto="680", borde="5", tipoborde="groove"):
        Frame.__init__(self)
        self.master=master
        self.config(bg=color,width=ancho,height=alto,bd=borde,relief=tipoborde)
    self.pack()


#Configuración del widget frame
mainframe1=marco(master="root")

#Ejecución de la ventana principal
root.mainloop()

问题是代码“有效”,当我运行该代码时,它显示主框架的根没有问题,但是当我尝试关闭根时,它不会关闭并抛出此错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\konoe\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
  File "C:\Users\konoe\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2061, in destroy
for c in list(self.children.values()): c.destroy()
  File "C:\Users\konoe\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2306, in destroy
if self._name in self.master.children:
AttributeError: 'str' object has no attribute 'children'

标签: pythontkinterframes

解决方案


问题是您传递了一个字符串作为master参数的值。该参数必须是一个小部件,而不是一个字符串。

mainframe1=marco(master=root)

您还应该将该参数传递给该__init__方法:

Frame.__init__(self, master)

严格来说,这个特定的代码没有必要,因为主窗口的默认值是根窗口。但是,如果您要创建一个子类,Frame则应始终在构造函数中包含主类,以便小部件可以在根窗口以外的地方使用。


推荐阅读