Skip to main content
 首页 » 编程设计

python之源代码不会在 python 2.7.10 中运行

2024年10月24日16shangdawei

我是一个 python 新手,在第 10 章中遇到了以下内容:

当我在 python 2.7.10 中运行代码时,它给出:

Traceback (most recent call last): 
File "C:\Users\Dave\learnpython\py3e_source\chapter10\click_counter.py", line 32, in <module> 
app = Application(root) 
File "C:\Users\Dave\learnpython\py3e_source\chapter10\click_counter.py", line 10, in __init__ 
super(Application, self).__init__(master) 
TypeError: must be type, not classobj 

这本书是写在理解python 3>上的,会用到。但是我能做些什么来解决 2.7.10 中的这个问题吗?我不知道该怎么做。

原始代码,除了'from tkinter'被更改为'from Tkinter':

# Click Counter 
# Demonstrates binding an event with an event handler 
 
from Tkinter import * 
 
class Application(Frame): 
    """ GUI application which counts button clicks. """  
    def __init__(self, master): 
        """ Initialize the frame. """ 
        super(Application, self).__init__(master)   
        self.grid() 
        self.bttn_clicks = 0    # the number of button clicks 
        self.create_widget() 
 
    def create_widget(self): 
        """ Create button which displays number of clicks. """ 
        self.bttn = Button(self) 
        self.bttn["text"]= "Total Clicks: 0" 
        self.bttn["command"] = self.update_count 
        self.bttn.grid() 
 
    def update_count(self): 
        """ Increase click count and display new total. """ 
        self.bttn_clicks += 1 
        self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks) 
 
# main 
root = Tk() 
root.title("Click Counter") 
root.geometry("200x50") 
 
app = Application(root) 
 
root.mainloop() 

请您参考如下方法:

我没有在任何项目中使用 Tk,但我怀疑 Frame 不是使用新样式类创建的,并且 super() 仅适用于新样式( https://docs.python.org/2/library/functions.html#super ) .尝试将您的 __init__ 方法更改为:

def __init__(self, master): 
    """ Initialize the frame. """ 
    Frame.__init__(self, master)   # <-- CHANGED   
    self.grid() 
    self.bttn_clicks = 0 
    self.create_widget()