assign a button be a word in a wordlist

Viewed 40

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. 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)
1 Answers

You can simplify things by using lambda functions for the command parameter of each button instead of using Game directly.

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>

Related