我做了一个小脚本来练习 tkinter 的使用。我希望程序打开一个窗口并显示一个标签。按下按钮后,标签应显示 0 到 100 之间的随机数。另外我希望标签每秒刷新一次并显示另一个随机数。
from tkinter import *
import random
import time
root = Tk()
def getrandint():
result = random.randint(0, 100)
return result
def go():
lab2['text'] = 'Number: ' + str(getrandint())
lab2.pack()
root.geometry('300x200')
root.mainloop()
time.sleep(1)
go()
lab1 = Label(root, text='Type in number')
lab2 = Label(root, text='Number:')
#ent = Entry(root, width=20)
#number = ent.get()
b = Button(root, text='Go', command=go())
b.pack()
lab1.pack()
lab2.pack()
#ent.pack()
这就是我走多远。它会打开一个窗口并显示一个随机数,但不会刷新该数字。按钮甚至没有显示。此外,当我关闭窗口时,Python 3.8 会显示以下错误消息:
Traceback (most recent call last):
File "C:/Users/chris/Desktop/WeatherLinkPy/testing.py", line 102, in <module>
b = Button(root, text='Go', command=go())
File "C:/Users/chris/Desktop/WeatherLinkPy/testing.py", line 95, in go
go()
File "C:/Users/chris/Desktop/WeatherLinkPy/testing.py", line 89, in go
lab2['text'] = 'Number: ' + str(getrandint())
File "C:\Users\chris\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1660, in __setitem__
self.configure({key: value})
File "C:\Users\chris\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1649, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\chris\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1639, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".!label2"
最后,有没有办法改变random.randint(0, b) 的第二个参数,在开头加上一个入口和一个按钮?