【发布时间】: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