ValueError:int()以10为底的无效文字:”随机数生成器

时间:2019-05-02 19:23:29

标签: python python-3.x

我试图允许创建的按钮在Tkinter中随机生成一个值,但我不断收到错误提示

  

ValueError:以10为底的int()无效文字:

from tkinter import *
from random import *
global playedNumber

class Paul_Lottery:
    def __init__(self):
        self.winningNumber = randrange(1,10)
        self.userInterface = Tk()
        self.playedNumber = 0


        Label(self.userInterface,text ='Type in your name').pack()
        Entry(self.userInterface,width =100).pack()

        Label(self.userInterface,text= 'Enter a number from 1-10:').pack()
        Entry(self.userInterface,width = 100).pack()
        self.justinNumber = Entry(self.userInterface,width=100)


        self.RandomButton= Button(self.userInterface,text = 'Play',command = self.CheckNumber).pack()
        self.finalresult = StringVar()
        self.finalresultLabel=Label(self.userInterface, textvariable = self.finalresult).pack()
        self.userInterface.mainloop()

    def CheckNumber(self):
            playedNumber = int(self.justinNumber.get())

            if playedNumber==self.winningNumber:
                self.finalresult.set('you are a winner')
            else:
                self.finalresult.set('the winning number is' + str(self.winningNumber) + 'you are not a winner')




def main():
     paul_lottery = Paul_Lottery()

main()

我知道该字符串必须转换为浮点数,但由于我已经将playNumber设置为0(作为整数),因此对如何执行此操作感到困惑。

2 个答案:

答案 0 :(得分:0)

您似乎正在尝试将字符串转换为整数,但是该字符串可能包含无法转换为int的内容。您应该通过捕获ValueError异常来处理此问题。例如

try:
   playedNumber = int(self.justinNumber.get())
except ValueError as e:
   # Do something reasonable when this error occurs such as
   # 1. Logging an error to help you debug
   # 2. Resetting the widget to a valid state
   # 3. Give the user some feedback (such as a warning message)
   print('Failed to convert to int {}'.format(e))

答案 1 :(得分:0)

您正在将一个空字符串(即'')传递给int()方法,这就是您的错误告诉您的内容。在我看来,您是在RandomButton字段中未输入任何内容的情况下按下了justinNumber(因此是一个空字符串),或者您的CheckNumber()方法在某种程度上被自动触发在您的justinNumber字段中输入一个猜测。我认为这就是您的错误出处。请注意,您的CheckNumber()方法仍在此字段中寻找猜测,而不是检查随机数。

要让按钮随机生成一个数字,您如何创建一个新方法,将其命名为random_guess(),如下所示:

def random_guess(self):
    guess = np.random.randint(1, 10)
    if guess == self.winningNumber:
        self.finalresult.set('you are a winner')
    else:
        self.finalresult.set('the winning number is' + str(self.winningNumber) + 'you are not a winner')

然后将其与您的随机按钮绑定:

self.RandomButton = Button(self.userInterface, text='Play',
                           command=self.random_geuss).pack()

如果您想花哨的话,建议您在random_guess()CheckNumber()之前自行寻找一种减少重复代码的方法!