0

这是我在 Stackoverflow 上的第一个问题。我已经学习 Python 一段时间了,但我并没有真正理解我的代码有什么问题。每次我运行我的程序,我都会得到这个错误:

Traceback (most recent call last):
File "D:\Python\guess the number gui.py", line 63, in <module>
app = Application(root)
File "D:\Python\guess the number gui.py", line 14, in __init__
self.create_widgets()
File "D:\Python\guess the number gui.py", line 37, in create_widgets
command = self.check_number()
File "D:\Python\guess the number gui.py", line 44, in check_number
guess = int(self.guess.get())
ValueError: invalid literal for int() with base 10: ''

这是代码:

from tkinter import *
import random

class Application(Frame):
    """ GUI application for the "Guess my number" game"""

    def __init__(self, master):
        """Initialize Frame. """
        super(Application, self).__init__(master)
        self.the_number = random.randint(1,100)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """Create widgets to get the number and show if it's correct"""
        # create instruction label
        Label(self,
              text = "I'm thinking of a number between 1-100. Can you guess it?"
              ).grid(row = 0, column = 0, columnspan = 2, sticky = W)

        # create label and text entry for the guess
        Label(self,
              text = "Guess: "
              ).grid(row = 1, column = 0, sticky = W)
        self.guess = Entry(self)
        self.guess.grid(row = 1, column = 1, sticky = W)

        # create a text field
        self.correct_txt = Text(self, width = 40, height = 5, wrap = WORD)
        self.correct_txt.grid(row = 3, column = 0, columnspan = 2)        

        # create a submit button
        Button(self,
               text = "Click to submit",
               command = self.check_number()
               ).grid(row = 2, column = 0, sticky = W)


    def check_number(self):

        # get the guess of the user
        guess = int(self.guess.get())

        # see if the guess is correct or wrong
        if guess == self.the_number:
            text = ("Congratulations, you guessed it! And it only took you", tries, "tries!")
            self.correct_txt.delete(0.0, END)
            self.correct_txt.insert(0.0, text)

        elif guess < self.the_number:
            text = "Higher..."
            self.correct_txt.delete(0.0, END)
            self.correct_txt.insert(0.0, text)

        elif guess > self.the_number:
            text = "Lower..."
            self.correct_txt.delete(0.0, END)
            self.correct_txt.insert(0.0, text)

# main
root = Tk()
root.title("Guess the number")
app = Application(root)
root.mainloop()

有人可以告诉我有什么问题吗?提前致谢!

4

1 回答 1

3

Button,command应该指命令的名称,而不是对命令的调用。正如您现在所拥有的,self.check_number()在创建按钮时被调用。尝试这个:

Button(self,
       text = "Click to submit",
       command = self.check_number
       ).grid(row = 2, column = 0, sticky = W)
于 2013-05-09T12:35:01.057 回答