Python Tkinter如何获取按钮触发的随机数生成函数返回的骰子值
掷骰子代码修改方案
核心调整是把生成的骰子值存储到函数外部可访问的位置,保留原有点击展示功能的同时支持外部取值。
方案1:全局变量实现(改动最小,适合小型项目)
from tkinter import * import random window=Tk() window.geometry("400x400") # 定义全局变量存储最新骰子值 current_dice_value = 0 l1=Label(window) def roll(): global current_dice_value # 生成随机数同时更新全局变量 current_dice_value = random.randint(1,6) l1.config(text=f'{current_dice_value}') l1.pack() # 如果有其他要触发的关联逻辑,直接在这里调用即可,比如: # your_custom_logic(current_dice_value) b1=Button(window,text="Roll the Dice!",foreground='blue',command=roll) b1.pack() window.mainloop()
使用说明:其他逻辑需要取值时,直接读取current_dice_value变量即可获取最新的骰子数值。
方案2:类封装实现(避免全局变量污染,适合中大型项目)
from tkinter import * import random class DiceGame: def __init__(self, root): self.root = root self.root.geometry("400x400") # 实例属性存储最新骰子值 self.current_dice = 0 self.l1 = Label(root) self.b1 = Button(root,text="Roll the Dice!",foreground='blue',command=self.roll) self.b1.pack() def roll(self): self.current_dice = random.randint(1,6) self.l1.config(text=f'{self.current_dice}') self.l1.pack() # 同样可以在这里直接调用其他关联逻辑 # self.your_custom_logic() if __name__ == "__main__": window = Tk() app = DiceGame(window) window.mainloop()
使用说明:其他逻辑需要取值时,直接读取app.current_dice属性即可获取最新的骰子数值。
重复点击不更新问题说明
之前遇到的数值不更新问题,大概率是变量作用域写错,或者错误把随机数生成逻辑放到了循环/初始化代码之外,上述两种方案都已规避该问题,多次点击会正常更新展示内容和存储的变量。
内容的提问来源于stack exchange,提问作者Beth Kux
相关产品推荐
相关产品推荐

