首页 > 解决方案 > 如何使用 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}

我希望有一个能够阻止数字再次滚动的按钮。

标签: pythontkinter

解决方案


不确定这是否是您要查找的内容,但您可以创建一个具有 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

推荐阅读