Open In App

Rock Paper and Scissor Game Using Tkinter

Improve
Improve
Like Article
Like
Save
Share
Report

Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications.

Prerequisite: Tkinter, random

In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”.

Game Winner Condition:

  • Paper and Scissor =>Scissor win
  • Rock and Scissor =>Rock win
  • Paper and Rock =>Paper win

Below is what the GUI looks like as follows: 

GUI Implementation Steps (Add Button, Label, Frame)

  • Create a head label that will show the title of the game, set its font and properties
  • Below the head, label create a user label that will show the hand sign selected by the user
  • Create a computer label that will show hand sign picked by the computer
  • In between the user and the computer label create a label to show the text “vs”
  • Create a result label to show the result set font and other properties to it
  • Create three pushbuttons for rock, paper, and scissor respectively
  • Create a reset button to reset the game.

Backend Implementation Steps:

We will create five functions; one is for reset the game, the second is for disabling the button and the other are for game winners

Implementation:

Python3




# Import Required Library
from tkinter import *
import random
 
# Create Object
root = Tk()
 
# Set geometry
root.geometry("300x300")
 
# Set title
root.title("Rock Paper Scissor Game")
 
# Computer Value
computer_value = {
    "0": "Rock",
    "1": "Paper",
    "2": "Scissor"
}
 
# Reset The Game
 
 
def reset_game():
    b1["state"] = "active"
    b2["state"] = "active"
    b3["state"] = "active"
    l1.config(text="Player              ")
    l3.config(text="Computer")
    l4.config(text="")
 
# Disable the Button
 
 
def button_disable():
    b1["state"] = "disable"
    b2["state"] = "disable"
    b3["state"] = "disable"
 
# If player selected rock
 
 
def isrock():
    c_v = computer_value[str(random.randint(0, 2))]
    if c_v == "Rock":
        match_result = "Match Draw"
    elif c_v == "Scissor":
        match_result = "Player Win"
    else:
        match_result = "Computer Win"
    l4.config(text=match_result)
    l1.config(text="Rock            ")
    l3.config(text=c_v)
    button_disable()
 
# If player selected paper
 
 
def ispaper():
    c_v = computer_value[str(random.randint(0, 2))]
    if c_v == "Paper":
        match_result = "Match Draw"
    elif c_v == "Scissor":
        match_result = "Computer Win"
    else:
        match_result = "Player Win"
    l4.config(text=match_result)
    l1.config(text="Paper           ")
    l3.config(text=c_v)
    button_disable()
 
# If player selected scissor
 
 
def isscissor():
    c_v = computer_value[str(random.randint(0, 2))]
    if c_v == "Rock":
        match_result = "Computer Win"
    elif c_v == "Scissor":
        match_result = "Match Draw"
    else:
        match_result = "Player Win"
    l4.config(text=match_result)
    l1.config(text="Scissor         ")
    l3.config(text=c_v)
    button_disable()
 
 
# Add Labels, Frames and Button
Label(root,
      text="Rock Paper Scissor",
      font="normal 20 bold",
      fg="blue").pack(pady=20)
 
frame = Frame(root)
frame.pack()
 
l1 = Label(frame,
           text="Player              ",
           font=10)
 
l2 = Label(frame,
           text="VS             ",
           font="normal 10 bold")
 
l3 = Label(frame, text="Computer", font=10)
 
l1.pack(side=LEFT)
l2.pack(side=LEFT)
l3.pack()
 
l4 = Label(root,
           text="",
           font="normal 20 bold",
           bg="white",
           width=15,
           borderwidth=2,
           relief="solid")
l4.pack(pady=20)
 
frame1 = Frame(root)
frame1.pack()
 
b1 = Button(frame1, text="Rock",
            font=10, width=7,
            command=isrock)
 
b2 = Button(frame1, text="Paper ",
            font=10, width=7,
            command=ispaper)
 
b3 = Button(frame1, text="Scissor",
            font=10, width=7,
            command=isscissor)
 
b1.pack(side=LEFT, padx=10)
b2.pack(side=LEFT, padx=10)
b3.pack(padx=10)
 
Button(root, text="Reset Game",
       font=10, fg="red",
       bg="black", command=reset_game).pack(pady=20)
 
# Execute Tkinter
root.mainloop()


 
 

Output:

 

Code Explanation:

  1. The code first creates an instance of the Tkinter root object.
  2. Next, it sets the geometry of the window to be 300×300 pixels.
  3. The title of the window is also set.
  4. Finally, a list called computer_value is created and initialized with three values: Rock, Paper, and Scissors.
  5. Next, a function named reset_game() is defined.
  6. This function will be used to initialize all of the game elements (b1 through b3) at once.
  7. In this function, each game element’s state (Rock, Paper, or Scissors) is set to “active”.
  8. Finally, the function ends by calling another function named analyze which will display all of the game information in a dialog box.
  9. The code first imports the required library, Tkinter.
  10. After that, it creates an object named root and sets its geometry to be 300×300.
  11. Next, it sets the title of the game to Rock Paper Scissor Game.
  12. Next, the code defines a variable called computer_value which will store three values: 0 for Rock, 1 for Paper and 2 for Scissors.
  13. The next line of code initializes the computer_value variable with these values.
  14. The last line of code in this snippet is called reset_game().
  15. This line instructs the game to set all three states of the b1[], b2[], and b3[] variables to “active”.
  16. The code starts by creating three variables: b1, b2, and b3.
  17. The first two (b1 and b2) are boolean variables that will store information about the state of the buttons.
  18. The third variable (b3) is a text variable that will store the name of the button.
  19. The next line of code sets up a simple if statement to check whether the player has selected rock or not.
  20. If the player has selected rock, then computer_value[str(random.randint(0,2))] will be “Rock”.
  21. This value is stored in c_v and it will be used later in the code to determine what action to take.
  22. Next, an Analyze() function is created.
  23. This function takes one parameter: str(random.randint(0,2)).
  24. This parameter tells the Analyze() function which number to use as input for randomizing between 0 and 2 (inclusive).
  25. So if you wanted to randomly choose between 1 and 3 instead of 0 and 2, you would replace “random.randint” with “random.”
  26. in this line of code.
  27. The next line of code calls the Analyze() function with str(random.randint(0,
  28. The code firstly defines three variables – b1, b2 and b3.
  29. These variables will each hold a boolean value, which will indicate the state of the button – i.e.
  30. whether it is enabled or disabled.
  31. Next, the code checks to see if the player has selected rock as their choice for the game.
  32. If they have, then the code sets the variable c_v to “Rock”, and proceeds to execute various other code blocks depending on this value.
  33. If c_v is not “Rock”, then the code block checks to see if computer_value[str(random.randint(0,2))] is equal to “Rock”.
  34. If it is, then this means that the computer has
  35. The code starts by creating two labels, l1 and l4.
  36. The first label, l1, will display the computer’s value in the text box.
  37. The second label, l4, will display the player’s value in the text box.
  38. Next, the code creates three buttons: button_disable(), button_enable(), and ispaper().
  39. The button_disable() function disable the button.
  40. The button_enable() function enables the button.
  41. Finally, ispaper() determines whether or not the player selected paper (by checking to see if c_v equals “Paper”).
  42. If it does, then match_result will be set to “Match Draw.”
  43. Otherwise, match_result will be set to “Computer Win.”
  44. Now let’s look at each part of this code in more detail.
  45. The first line of code creates a variable called c_v.
  46. This variable stores information about which type of rock-paper-scissors game has been started (computer vs. player).
  47. The next line of code sets c_v to equal computer_value[str(random.randint(0, 2))].
  48. This line uses a random number generator to create a new string that stores the computer’s
  49. The code will display different messages depending on the value of the c_v variable.
  50. If c_v is equal to “Rock”, then the code will print out “Computer Win”.
  51. If c_v is equal to “Scissor”, then the code will print out “Match Draw”.
  52. Finally, if c_v is any other value, then the code will print out “Player Win”.
  53. To disable the buttons, you can use the following code: button_disable() method. 


Last Updated : 29 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads