Creating an Exe File for a GUI Game Practice Program in Python Tkinter for Beginners

Posted by


In this tutorial, we will be creating a simple aiming exercise game using Python’s tkinter module. This game will help you practice your aiming skills by clicking on targets that appear on the screen. We will also learn how to convert the Python script into an executable (.exe) file using PyInstaller.

Step 1: Setting up the GUI
First, let’s import the necessary modules and create a basic tkinter window for our game. Create a new Python script and add the following code:

import tkinter as tk

# Create the main window
root = tk.Tk()
root.title("Aim Exercise Game")

# Set the window size
root.geometry("400x400")

# Add a canvas for displaying the targets
canvas = tk.Canvas(root, width=400, height=400, bg="white")
canvas.pack()

# Run the main loop
root.mainloop()

Run the script to see the empty window. We will now add the functionality for creating and displaying targets on the canvas.

Step 2: Adding Targets
Let’s create a function that generates targets on the canvas at random positions. We will use the create_oval method of the canvas to draw circles as targets.

Add the following code to your script:

import random

def create_target():
    x = random.randint(10, 390)
    y = random.randint(10, 390)
    canvas.create_oval(x-10, y-10, x+10, y+10, fill="red")

# Call the function to create a target
create_target()

Run the script and you should see a red circle representing a target on the canvas.

Step 3: Adding Click Events
Now, let’s add functionality to detect when the user clicks on a target. We will use the bind method of the canvas to register a click event handler.

Add the following code to your script:

def on_click(event):
    item = canvas.find_closest(event.x, event.y)
    tags = canvas.gettags(item)

    if "target" in tags:
        canvas.delete(item)

canvas.bind("<Button-1>", on_click)

This code defines a function on_click that gets called whenever the user clicks on the canvas. It checks if the clicked item is a target and deletes it if it is. We need to modify the create_target function to assign the "target" tag to the created oval:

def create_target():
    x = random.randint(10, 390)
    y = random.randint(10, 390)
    target = canvas.create_oval(x-10, y-10, x+10, y+10, fill="red")
    canvas.addtag_withtag("target", target)

Now, when you run the script and click on the target, it should disappear.

Step 4: Converting to .exe File
To convert our Python script into an executable (.exe) file, we will use PyInstaller. First, install PyInstaller by running:

pip install pyinstaller

Create a spec file for PyInstaller by running:

pyi-makespec aim_game.py

Modify the spec file aim_game.spec to include the necessary imports and settings:

hiddenimports=['tkinter', 'random'],

Finally, build the executable by running:

pyinstaller aim_game.spec

This will generate a dist folder containing the .exe file of your game.

Congratulations! You have successfully created a simple aiming exercise game using tkinter and converted it into an executable file. You can now share your game with others without requiring them to have Python installed. Happy gaming!

0 0 votes
Article Rating
29 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@user-vh4pe4fo4p
1 month ago

너무 깔끔하게 잘 알려 주셔서 감사합니다!

@soohyunjeon9348
1 month ago

❤❤❤대박 센스이십니다!!! 마무리까지~!!! 좋은 영상 감사합니다~!!! ❤❤❤

@kane-donation
1 month ago

아이고.. 어떻게 해도 계속 pyinstaller는 내부 또는 외부명령, 실행할 수 있는 프로그램 또는 배치파일이 없다고 뜨네요. 살려주세요

@kimjeakwon2204
1 month ago

저는 주피터가 아니라 비주얼스튜디오코드 인데 이럴때 뭘 눌러야하는지 모르겠네요

@user-mg3ci9do5d
1 month ago

참 감사합니다 도움이 엄청많이 되었습니다

@jeakwonit1414
1 month ago

저가 주피터말고 비주얼스튜디오 쓰는데 파일 저장하는거 어떻게 하는건지 모르겠어요ㅜㅜ

@brightman_praise
1 month ago

유용한 강의였습니다. 감사합니다.

@더_브로콜리
1 month ago

설명이 진짜 쉽네요
혹시 이거 따라만들어서 친구한테 따라만든 프로그램을 공유해도 될까요?

@spectrum8200
1 month ago

썜~ 따라하다가 궁금한게 생겨서 질문 남겨용

k=1
def click_new():

global k

k+=1

k=1이라고 위에서 변수로 써줫는데
def에서 global k라고 하는 건 왜일까요?

k=1이 def 보다 인덴트 상 상위?이니깐 global을 굳이 쓰지 않더라도 되지 않나요? (해보니 선언 전에 할당했다는 오류가 뜨지만요..ㅠㅠ)

@Jeong3187
1 month ago

처음 tkinter 를 접하는 사람에게 매우 좋은 영상입니다. 복받을겨~!

@ytubewiki
1 month ago

이 강좌를 통해서 성공적으로 실행파일을 만들었습니다.

@harveykim5231
1 month ago

고맙습니다. 몇 번의 고비가 있었지만, 같이 따라서 만들다보니 하나 성공했네요. ^^

@user-mk3tc4pw6o
1 month ago

aim 파일을 zip파일로 만들어 메일로 보내려 하는데 바이러스가 발견되었다고 안 보내집니다.
바이러스 검사를 했더니 바이러스는 없다는데…
혹시 어떻게 해결할 수 있을까요?

@user-hs1co6dv7o
1 month ago

질문있는데요 완성된프로그램이 있는데 그프로그램 코드를 볼려면 어떻게 해야하나요?

@user-cd6oc7mc6f
1 month ago

idle 파이썬은 파일 다운로드가 안돼나요?

@user-vc6dq6hi2h
1 month ago

좋은강의 너무 감사합니다ㅠㅠ

@user-xf8dj6ll4d
1 month ago

친절한 강의에 감사드립니다.
exe 파일로 저장하려고 강의 내용과 함께 저장했는데, 그냥 .py로 저장되는군요.
지금은 안되는지요?

@user-rh3cz2ee6x
1 month ago

Exe 파일로 변환해서 다른분에게 드리면 만든 로직도 상대방이 볼수 있나용. 로직없이 실행만 될수 있게 했으면 해서용.

@hyeyoon_kim
1 month ago

설명 쉽게 해 주셔서 너무 감사합니다 🙂 매주 보면서 학습하고 있어요!

@user-mg1to5lj9g
1 month ago

잘봤습니다!
다른 강의에서 만든 셀레니움을 통해 만든
예매와같은 것도 .exe로 실행가능할까요?