如何使用Tkinter中的按钮来停止运行另一行代码?

2024-06-06 09:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个个人项目来尝试更好地使用python。我正在做的游戏是Yahtzee。我有它的设置,你可以滚动所有的模具,它会告诉你你有什么。我也有一个窗口设置使用Tkinter。我想做的是在每个数字下面都有一个按钮,上面写着“HOLD”。如果你知道yahtzee是怎么工作的,你就会知道为什么。我只想用这个按钮阻止骰子在你第一次掷骰子后再次滚动。你知道吗

我已经在这里查看了关于堆栈溢出的其他帖子,但是没有一个帖子妨碍了我一直在尝试的解决方法。你知道吗

# 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}

我希望有一个按钮,将能够阻止一个数字被再次滚动。你知道吗


Tags: 数字randomwindow按钮帖子rollrandinthold
2条回答

您可以对hold按钮使用Checkbutton,并检查它们的状态,以确定相应的骰子是否要在下一次掷骰时保持。下面是一个示例代码(使用Checkbutton作为骰子本身):

from tkinter import *
from random import randint

root = Tk()
root.title("Sam's Yahtzee")

def roll(dice, times):
    if times > 0:
        dice['text'] = randint(1, 6)
        root.after(10, roll, dice, times-1)

def roll_dices():
    for i in range(5):
        if dices[i][1].get() == 0:
            # dice is not held, so roll it
            roll(dices[i][0], 10)

dices = []
for i in range(5):
    ivar = IntVar()
    dice = Checkbutton(root, text=randint(1, 6), variable=ivar, bg='silver', bd=1, font=('Arial', 24), indicatoron=False, height=3, width=5)
    dice.grid(row=0, column=i)
    dices.append([dice, ivar])

Button(text='Dice', command=roll_dices, height=2, font=(None, 16, 'bold')).grid(row=1, column=0, columnspan=5, sticky='ew')

root.mainloop()

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

相关问题 更多 >