随机导入 从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()
答案 0 :(得分:1)
这应该有效
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()
您的代码的主要问题是,每次单击按钮时,您都必须创建一个新的随机数,并且必须更改同一标签的文本,否则您将需要堆叠一堆标签。
答案 1 :(得分:0)
您一次将随机数分配给random_number
变量,因此它永远不会改变。
如果将其移至方法,则每次都会生成一个新的方法。
import random from tkinter import * root = Tk()
def myClick():
random_number = str(random.randint(1,11)) # Generates a new # when the method is called.
myLable = Label(root, text=f"{random_number}") myLable.pack()
rand_button = Button(root, text="Press for a random number", command=myClick)
rand_button.pack()
root.mainloop()