I am working on a Python project that is a rock paper scissors game with a Tkinter GUI (Just began to code in Python). I have made buttons to click and want them to add an int to playerChoice
. playerChoice
is a variable that is either a 1,2 or 3. 1 is rock, 2 is paper and 3 is scissors. I cannot figure out how to do this. I have already made a function that adds 1 to playerChoice when I click the rock button but still it still will not work. The code looked a bit like this:
playerChoice = 0
def rockSelected(pC):
pC += 1
rockButton = Button(window, text="Rock", command=rockSelected(playerChoice))
But it just did not print when I tried to print "rock" if playerChoice = 1 I do not know what I should do right now here is what I have
window = tkinter.Tk()
window.title("Rock Paper Scissors")
window.geometry('600x400')
winLabel = Label(window, text="You won")
loseLabel = Label(window, text="You lose")
drawLabel = Label(window, text="It is a draw")
rockButton = Button(window, text="Rock")#, command= has to give me an int value of 1
rockButton.pack()
"""Make an if statement to check
if it is rock paper or scissors
like this
if value == 1:
playerchoice = 1
playerchoice is rock paper or scissors"""
rockButton.place(bordermode=OUTSIDE, height=30, width=60, x=100, y=100)
paperButton = Button(window, text="Paper")
paperButton.pack()
paperButton.place(bordermode=OUTSIDE, height=30, width=60, x=230, y=100)
def main():
pass
if __name__ == '__main__':
main()
window.mainloop()
Copy comment: now my code looks like this
# Instantiate a Button widget with parent=window rockButton = Button(window, text="Rock") # bind the function `playerChoice` # to the "<Button-1>" event (left mouse button) rockButton.bind("<Button-1>", playerChoice) # Layout the Button widget in the parent widget == window rockButton.pack() # Define a function to used as event callback # Needs to have a `event` parameter def playerChoice(event): # Get the bound widget from the `event` object w = event.widget # <= the Button widget # The widget is of type `Button` # Get the Button `text=` choice = w['text'] # Print the event.widget['text'] value print('Player choice:{}'.format(choice)) # Do according to the `choice` the actions if choice == 'Rock': # Do the Rock action pass elif choice == 'Paper': # Do the Paper action pass