简体   繁体   English

将按钮指定为单词列表中的单词

[英]assign a button be a word in a wordlist

I am making this Rock Paper Scissors game based on just image buttons to resemble rock paper scissors.我正在制作这款石头剪刀布游戏,仅基于图像按钮来模仿石头剪刀布。

But now i want to assign a button to be "Rock" from my list.但现在我想从我的列表中指定一个按钮为“Rock”。 How would i do that?我该怎么做? code:代码:

    #Options
def Game():
    choice = ["Rock", "Paper", "Scissors"]
    RockButton = choice[0]
    PaperButton = choice[1]
    ScissorsButton = choice[2]

    #Naming the images
RockButton = Button(root, image = rock, bg="white", bd=0,command=Game).pack(side = LEFT)
PaperButton = Button(root, image = paper, bg="white", bd=0,command=Game).pack(side = RIGHT)
ScissorsButton = Button(root, image = scissors, bg="white", bd=0, command=Game).pack(pady=10)

You can simplify things by using lambda functions for the command parameter of each button instead of using Game directly.您可以通过对每个按钮的command参数使用 lambda 函数来简化事情,而不是直接使用Game

def Game(player_choice_string):
    print("player chose: {}".format(player_choice_string))

(RockButton := Button(root, image = rock, bg="white", bd=0,command=lambda:Game("rock"))).pack(side = LEFT)
(PaperButton := Button(root, image = paper, bg="white", bd=0,command=lambda:Game("paper"))).pack(side = RIGHT)
(ScissorsButton := Button(root, image = scissors, bg="white", bd=0, command=lambda:Game("scissors"))).pack(pady=10)

The walrus operator ( := ) works in python >= 3.8 For older versions, you can just split the Button() and .pack() call onto two lines as shown here: Tkinter: AttributeError: NoneType object has no attribute <attribute name> The walrus operator ( := ) works in python >= 3.8 For older versions, you can just split the Button() and .pack() call onto two lines as shown here: Tkinter: AttributeError: NoneType object has no attribute <attribute name >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM