【问题标题】:Rolling two dice vía Buttons通过按钮掷两个骰子
【发布时间】:2021-04-30 19:19:28
【问题描述】:

我正在尝试创建两个骰子,它们可以一起滚动,或者如果标记为keep,则分别滚动。我尝试了以下代码。 roll_dice 按钮掷骰子。使用 botton1 和 botton2 可以将每个骰子标记为keep,因此如果按下roll_dice,则不会滚动。

import tkinter
import random

# toplevel widget of Tk which represents mostly the main window of an application
root = tkinter.Tk()
root.geometry('1200x600')
root.title('Roll Dice')

# label to display dice
label = tkinter.Label(root, text='', font=('Helvetica', 260))

# function activated by button
def switch1():
    button1["state"] = "disabled"
    
def switch2():
    button2["state"] = "disabled"

def roll_dice(var1, var2):
    # unicode character strings for dice
    dice = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']

    
    if button1["state"] == "active" and button2["state"] == "active":
        var1 = f'{random.choice(dice)}'
        var2 = f'{random.choice(dice)}'
        label.configure(text= var1 + var2)
        label.pack()
    elif button1["state"] == "active":
        var2 = f'{random.choice(dice)}'
        label.configure(text= var1+var2)
        label.pack()
    elif button2["state"] == "active":
        var1 = f'{random.choice(dice)}'
        label.configure(text= var1 + var2)
        label.pack()

    
# button
dice = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']
var1, var2 = [f'{random.choice(dice)}', f'{random.choice(dice)}']


button1 = tkinter.Button(root, text='keep', foreground='green', command=switch1, state = "active")
button2 = tkinter.Button(root, text='keep', foreground='green', command=switch2, state = "active")
button_roll = tkinter.Button(root, text='roll dice', foreground='green', command=lambda: roll_dice(var1, var2))
   
# pack a widget in the parent widget
button_roll.pack()
button1.pack()
button2.pack()

# call the mainloop of Tk
# keeps window open
root.mainloop()

当我运行代码时,标记为keep 的骰子会再次滚动一次。之后,当我掷骰子时,骰子不会改变。怎么做才能不再滚动一次?

【问题讨论】:

  • 请发布完整的错误回溯。
  • 离题评论:单数是die,复数是dice

标签: python python-3.x tkinter


【解决方案1】:

command=roll_dice(var1, var2)) 是错误的,因为您正在调用函数而不是将其作为回调传递。要么使用 lambda,比如 command=lambda: roll_dice(var1, var2),要么为回调定义一个单独的函数。

【讨论】:

  • 谢谢,这行得通。但是在激活keep之后,骰子还是会变一次才变为非激活状态
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2017-01-18
  • 1970-01-01
  • 2012-02-29
  • 2015-06-26
相关资源
最近更新 更多