导入随机 从tkinter导入* 根= Tk()
random_number = str(random.randint(1,11))
def myClick(): myLable = Label(root,text = f“ {random_number}”) myLable.pack()
rand_button = Button(root,text =“ Press for an random number”, command = myClick) rand_button.pack()
root.mainloop()
这应该工作
import random
from tkinter import *
root = Tk()
random_number = str(random.randint(1, 11))
MyLabel = Label(Tk, text=random_number)
MyLabel.pack()
def myclick():
random_number = str(random.randint(1, 11)) # Assigning random number
MyLabel.config(text=random_number) # Changing text to random number
randButton = Button(root, text="Press for a random number", command=myClick)
randButton.pack()
root.manloop()
代码的主要问题是,每次单击按钮时,您都必须创建一个新的随机数,并且必须更改同一标签的文本,否则,一堆标签会相互堆叠。] >
您一次给random_number
变量分配了一个随机数,因此它永远不会改变。