Skip to main content
 首页 » 编程设计

Python 3.2,Tkinter 类声明,子类化时类未定义

2025年05月04日14qq号

我正在学习 python 并遇到似乎是来自 tkinter 的类装饰器的问题。只要我从不尝试用 Frame 装饰,我就可以让 tkinter 工作。下面的代码没有给我任何错误,也没有窗口。无论出于何种原因,我定义的类永远不会被定义。下面是我的代码。下面是我根据有关 tkinter 的类似问题所做的测试。

>>> from tkinter import * 
import tkinter 
class Apples: 
    def __init__(self, master): 
        frame = Frame(master) 
        frame.pack() 
        self.button = Button(frame, text="Quit", fg="blue", command=frame.quit) 
        self.button.pack(side=LEFT) 
        self.hellos = Button(frame, text="Hello", command=self.say_hello) 
        self.hellos.pack(side=LEFT) 
    def say_hello(self): 
        print("Hello World!") 
root = Tk() 
app = Apples(root) 
root.mainloop() 

没有窗口出现。没有错误。所以我检查类(class)...

>>> test = Apples(root) 
Traceback (most recent call last): 
  File "<pyshell#54>", line 1, in <module> 
    test = Apples(root) 
NameError: name 'Apples' is not defined 
>>>  

我发现了一个类似的问题Creating buttons with Python GUI并尝试了 pythonMan 的代码。我仍然遇到同样的类声明问题。

>>> from tkinter import *  
 
class Application(Frame): 
"""A GUI application with three button""" 
 
def __init__(self,master): 
    self.master = master 
    self.create_widgets() 
 
 
 
def create_widgets(self): 
    #"""Create three buttons""" 
    #Create first buttom 
    btn1 = Button(self.master, text = "I do nothing") 
    btn1.pack() 
 
    #Create second button 
    btn2 = Button(self.master, text = "T do nothing as well") 
    btn2.pack() 
 
    #Create third button 
    btn3=Button(self.master, text = "I do nothing as well as well") 
    btn3.pack() 
 
root = Tk() 
root.title("Lazy Button 2") 
root.geometry("500x500") 
app = Application(root) 
root.mainloop() 
>>> Application 
Traceback (most recent call last): 
  File "<pyshell#58>", line 1, in <module> 
    Application 
NameError: name 'Application' is not defined 
>>>  

我认为有些东西没有被正确声明,但没有产生语法错误。任何帮助将不胜感激。

请您参考如下方法:

我认为你不需要“>>>”标志。

“从 Tkinter 导入 *”