源代码不会在python2.7.10中运行

2024-04-25 07:47:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

这本书是关于理解python3>;将会被使用的。但是我能在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()

Tags: 代码fromselfmasterapplicationinitdefcount
1条回答
网友
1楼 · 发布于 2024-04-25 07:47:32

我没有在任何项目中使用过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()

相关问题 更多 >