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) の 2 番目のパラメータを変更する方法はありますか?