python - 如何使用 Tkinter 中的按钮来停止运行不同的代码行?
问题描述
我正在创建一个个人项目以尝试在 python 方面做得更好。我正在制作的游戏是 Yahtzee。我把它设置在你可以滚动所有骰子的地方,它会告诉你你有什么。我也有一个使用 Tkinter 的窗口设置。我想要做的是在每个数字下方有一个按钮,上面写着“HOLD”。如果你知道 yahtzee 是如何工作的,你就会知道为什么。我只是想让这个按钮在你第一次掷骰后停止掷骰子。
我在 Stack Overflow 上查看了其他帖子,但没有一个帖子是我一直试图弄清楚的。
# Window
def hold():
window = Tk()
window.title("Sam's Yahtzee")
window.configure(background="black")
Button(window, text="HOLD", width=6, command=hold) .grid(row=3, column=0,
sticky=W)
window.mainloop()
# Dice Roll
roll1 = random.randint(1, 6)
roll2 = random.randint(1, 6)
roll3 = random.randint(1, 6)
roll4 = random.randint(1, 6)
roll5 = random.randint(1, 6)
print(roll1, roll2, roll3, roll4, roll5)
# Choosing What Num to Hold
# Roll Num Storing
userRollHold = {'roll1': roll1,
'roll2': roll2,
'roll3': roll3,
'roll4': roll4,
'roll5': roll5}
我希望有一个能够阻止数字再次滚动的按钮。
解决方案
不确定这是否是您要查找的内容,但您可以创建一个具有 hold 属性的类,并根据您的要求设置和取消设置:
例如:
class Dice:
def __init__(self):
self.held = False
self.val = None
def roll(self):
self.val = random.randint(1, 6) if not self.held else self.val
return self.val
def hold(self):
self.held = True
def unhold(self):
self.held = False
这是一个概念验证测试代码:
dice_1, dice_2, dice_3 = Dice(), Dice(), Dice()
print dice_1.roll(), dice_2.roll(), dice_3.roll()
dice_1.hold()
dice_3.hold()
print dice_1.roll(), dice_2.roll(), dice_3.roll()
print dice_1.roll(), dice_2.roll(), dice_3.roll()
dice_1.unhold()
print dice_1.roll(), dice_2.roll(), dice_3.roll()
输出:
5 3 5
5 1 5
5 6 5
3 1 5
推荐阅读
- git - 这种情况下最好的分支策略是什么?
- javascript - 有没有办法在 TypeScript 类中返回 express 实例?
- gremlin - 获取更多关于 Gremlin 遍历的数据而不仅仅是节点 ID?
- azure - 如何在没有/使用简单身份验证的情况下显示 Azure 监控仪表板?
- r - 如何将预测列表转换为R中的规范化表
- fft - 如何使用傅里叶变换计算动量矩阵元素?
- python-3.x - yt_search 在控制台中打印。如何删除它?
- pine-script - 我将如何在给定范围内仅使用牛市蜡烛进行一些计算?
- wordpress - WordPress elementor 插件中的错误 500
- git - 在 git log / git show 中显示复制的文件