代码返回错误?(Python)itemconfigure未定义?

2024-10-01 22:36:15 发布

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

你好,我在做计时器。这是我的密码:

from tkinter import*
import time
Screen=Tk()
Screen.resizable(0,0)
myText=Label(Screen,text="Welcome To X Timer!",font=(None,50),bg="green")
myText.pack()
aText=Label(Screen,text="0:0",font=(None,30))
aText.pack()
def start_timer():
    x=1
    while(True):
        time.sleep(1)
        x=x+1
        itemconfigure(aText,text=x)
strBTN=Button(Screen,text="Start",bg="purple",font= 
("Helvetica",45),command=start_timer)
strBTN.pack()
Screen.mainloop()

但第14行写着:Error:itemconfigure is 未定义。请帮帮我


Tags: textimportnonetimescreenstartlabelpack
2条回答

现在还不清楚你到底想做什么,但是你的start_timer函数是一个无限繁忙的循环,它会挂起你的GUI,所以我假设这是而不是它!也许你想打电话给Tk.after

def start_timer(x=0):
    x+=1
    Screen.after(1000, lambda x=x: start_timer(x))
    # 1000 is the time (in milliseconds) before the callback should be invoked again
    # lambda x=x... is the callback itself. It binds start_timer's x to the scope of
    # the lambda, then calls start_timer with that x.
    itemconfigure(aText,text=x)

我冒昧地说你希望itemconfigure(aText, text=x)改变标签上的文字?您应该使用:

    ...
    aText.config(text=x)

要更改标签的文本,必须使用Label的方法config()。所以,代替itemconfigure(aText,text=x),做aText.config(text=x)。我认为itemconfigure()函数不存在

此外,还有其他问题。例如,如果将具有无限循环的函数定义为按钮回调,则按钮将始终保持按下状态(按钮保持按下状态直到回调完成)。这就是为什么我建议您在回调结束时使用Screen的方法after(),并使其执行相同的函数。 after()在输入的毫秒数之后执行函数,因此Screen.after(1000, function)将在一秒钟内暂停执行并执行函数。 还可以使用s变量来存储秒数。当s等于60时,它将重置为0,并在1分钟内增加(m)。 这里有代码:

from tkinter import*

Screen=Tk()
Screen.resizable(0,0)

myText=Label(Screen,text="Welcome To X Timer!",font=(None,50),bg="green")
myText.pack()

aText=Label(Screen,text="0:0",font=(None,30))
aText.pack()

def start_timer():
    global s, m, aText, Screen
    aText.config(text = str(m) + ":" + str(s))
    s += 1
    if s == 60:
        s = 0
        m += 1
  Screen.after(1000,start_timer)

s = 0
m = 0

strBTN=Button(Screen,text="Start",bg="purple",font=("Helvetica",45),command=start_timer)
strBTN.pack()

Screen.mainloop()

这个应该能用(在我的电脑里它能正常工作)。如果你不懂什么,就问吧

相关问题 更多 >

    热门问题