如何解决我怎样才能让两个骰子的结果显示在 python 的“计分箱”中?
这很简单,我希望在 GUI 某处的“计分箱”中显示组合的两个骰子的值。我试图到处寻找,但在任何地方都找不到简单的解决方案。任何人都可以帮助 python 菜鸟? :)
(代码是从 YouTube 教程中复制的,所以不是我的代码。)
import tkinter as tk
import random
#creating the GUI itself
root = tk.Tk()
root.geometry('600x400')
root.title('Roll Dice')
label = tk.Label(root,text='',font=('Helvetica',260))
#dice function
def roll_dice():
dice = ['\u2680','\u2681','\u2682','\u2683','\u2684','\u2685']
label.configure(text=f'{random.choice(dice)} {random.choice(dice)}')
label.pack()
#button to press to start rolling the dice
button = tk.Button(root,text='Roll Dice',foreground='black',command=roll_dice)
button.pack()
root.mainloop()
解决方法
您可以简单地映射字典中的文本,然后在键上使用索引来获取分数,然后只需添加分数即可。
dice = {'\u2680':1,'\u2681':2,'\u2682':3,'\u2683':4,'\u2684':5,'\u2685':6}
scorebox = tk.Label(root,font=('Helvetica',20)) # Make a scoresheet label
def roll_dice():
first,second = random.choice(list(dice)),random.choice(list(dice)) # Two random rolls
score_text = dice[first] + dice[second] # Corresponding texts
label.configure(text=f'{first} {second}') # Change the label
scorebox.configure(text=score_text)
label.pack()
scorebox.pack()
为什么字典定义在函数外?这样它只定义一次,不会在函数内部不必要地覆盖。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。