【问题标题】:Tkinter: 'str' object has no attribute 'children' when attempting to closeTkinter:“str”对象在尝试关闭时没有属性“children”
【发布时间】:2019-08-30 04:35:34
【问题描述】:

我正在尝试在 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'

【问题讨论】:

  • 试试Frame.__init__(self, master)?

标签: python tkinter frames


【解决方案1】:

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

mainframe1=marco(master=root)

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

Frame.__init__(self, master)

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

【讨论】:

    【解决方案2】:

    处理此问题的一种方法是将键与操作绑定:

    def quit(event):
        print "you pressed control c"
        root.quit()
    
    root = tk.Tk()
    root.bind('<Control-c>', quit)
    root.mainloop()
    

    另一种方法是使用退出按钮来安全地关闭 Tkinter 窗口。

    root=Tk()
    root.title("Cath Config")
    Button(root, text="Quit", command=quit).pack()
    
    def quit():
        global root
        root.quit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多