类型错误,但这两个变量都是整数

2024-06-16 17:13:11 发布

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

代码如下:

这里声明了startTimeendTime。我不确定是否应该使用IntVar或StringVar,因为它们以前不起作用。你知道吗

startTime = str
endTime = str

def start1():
    Canvas1 = Canvas(ReactionTest,width = 500,height = 450)
    Canvas1.grid(row=4,column=0,columnspan=3,pady=10)
    image_1 = PhotoImage(file="photo_1.gif")
    Canvas1.create_image(0,0,anchor=NW, image=image_1)
    Canvas1.image_1=image_1
    startTime = time.strftime('%S')
def end1():
    endTime = time.strftime('%S')
    calctimeTaken = int(endTime) - int(startTime)
    timeTaken = str(calctimetaken)

回溯:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\brent\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1702, in __call__
    return self.func(*args)
  File "C:\Users\brent\OneDrive\Desktop\Computer Science\Program\WonderWalls Program.py", line 810, in end1
    calctimeTaken = int(endTime) - int(startTime)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'type'

Tags: inimagetimedefcallusersfileint
2条回答

问题不在于你有两个单独的函数吗?默认情况下,变量的作用域不在函数之外。您可以通过在函数外部声明它们并使用“global startTime”在函数中声明它们,或者在函数外部声明它们,然后将它们作为参数传递到函数中来解决这个问题。你知道吗

我怀疑你是在从结束时间中减去空的什么

我认为问题是你的变量不是全局变量,你只在函数中声明变量。 请尝试使用以下代码:


startTime = 0
def start1():
    global startTime
    Canvas1 = Canvas(ReactionTest,width = 500,height = 450)
    Canvas1.grid(row=4,column=0,columnspan=3,pady=10)
    image_1 = PhotoImage(file="photo_1.gif")
    Canvas1.create_image(0,0,anchor=NW, image=image_1)
    Canvas1.image_1=image_1
    startTime = time.strftime('%S')
def end1():
    global startTime
    endTime = time.strftime('%S')
    calctimeTaken = int(endTime) - int(startTime)
    timeTaken = str(calctimetaken)

相关问题 更多 >