杰瑞科技汇

Python SimpleGUITk怎么用?

Of course! simpleguitk is a fantastic library for beginners to learn the fundamentals of programming and game development in Python. It's a simplified wrapper around the more complex simpleguitk library, which is itself a Pythonic version of Google's SimpleGUI framework used in their "Intro to Python" course.

Python SimpleGUITk怎么用?-图1
(图片来源网络,侵删)

Here's a complete guide covering what it is, how to install it, and how to build a simple game.


What is simpleguitk?

simpleguitk is a Python library that provides a very simple set of tools to create interactive graphical applications, primarily 2D games. Its main goal is to be easy to learn and use, abstracting away the complexities of more powerful libraries like Pygame or Pyglet.

Key Features:

  • Simple Event Handling: It uses callbacks (functions you define) to handle user input like mouse clicks, keyboard presses, and button clicks.
  • Built-in Drawing Functions: It comes with a set of simple drawing functions like canvas.draw_text(), canvas.draw_circle(), canvas.draw_polygon(), etc.
  • Game Loop: It manages a "frame" or "tick" event, which calls a function you define repeatedly. This is the heart of any game, allowing you to update the game state and redraw the screen many times per second.
  • Timer: It has a timer object to schedule functions to be called after a certain amount of time.

Installation

First, you need to install it. Since it's not part of the standard Python library, you'll use pip.

Python SimpleGUITk怎么用?-图2
(图片来源网络,侵删)
pip install simpleguitk

Basic Program Structure

Every simpleguitk program follows a similar pattern:

  1. Import the library: import simpleguitk as simplegui
  2. Define global variables: To store the state of your game (e.g., score, ball position, player health).
  3. Define event handler functions: These functions are called when an event occurs (e.g., key_down, mouse_click).
  4. Define the "draw" handler function: This function is called repeatedly (the game loop). It clears the canvas and redraws all the elements based on the current game state.
  5. Create the frame and canvas: Set up the main window.
  6. Start the frame: Tell simpleguitk to start running the event handlers and the draw loop.

Example 1: A Simple "Click the Circle" Game

This is a classic first game. A circle appears on the screen, and you get a point for clicking it. The circle then moves to a new random location.

Code

import simpleguitk as simplegui
import random
# 1. Define global variables
canvas_width = 600
canvas_height = 400
score = 0
circle_pos = [canvas_width / 2, canvas_height / 2]
circle_radius = 20
# 2. Define event handler functions
def draw(canvas):
    """This function is called repeatedly to draw the canvas."""
    # Clear the canvas
    canvas.draw_circle(circle_pos, circle_radius, 2, "Red", "White")
def mouse_click(pos):
    """This function is called when the mouse is clicked."""
    global score, circle_pos
    # Check if the click is inside the circle
    distance = ((pos[0] - circle_pos[0]) ** 2 + (pos[1] - circle_pos[1]) ** 2) ** 0.5
    if distance <= circle_radius:
        score += 1
        # Move the circle to a new random position
        circle_pos[0] = random.randrange(circle_radius, canvas_width - circle_radius)
        circle_pos[1] = random.randrange(circle_radius, canvas_height - circle_radius)
        print("Hit! Score:", score)
    else:
        print("Miss!")
# 3. Create the frame and canvas
frame = simplegui.create_frame("Click the Circle", canvas_width, canvas_height)
# 4. Register event handlers
frame.set_draw_handler(draw)
frame.set_mouseclick_handler(mouse_click)
# 5. Start the frame
frame.start()
print("Game started! Click the red circle to score.")

How to Run It

  1. Save the code as a Python file (e.g., click_game.py).
  2. Run it from your terminal: python click_game.py.
  3. A window should appear. Click the white circle to increase your score!

Example 2: A Simple Bouncing Ball

This example introduces the concept of a "game loop" to update the position of an object over time.

Code

import simpleguitk as simplegui
# 1. Define global variables
canvas_width = 600
canvas_height = 400
ball_radius = 20
ball_pos = [canvas_width / 2, canvas_height / 2]
ball_vel = [2, 2] # [x_velocity, y_velocity]
# 2. Define helper and event handler functions
def draw(canvas):
    """This function is called repeatedly to update and draw the canvas."""
    global ball_pos, ball_vel
    # Update ball position using velocity
    ball_pos[0] += ball_vel[0]
    ball_pos[1] += ball_vel[1]
    # Bounce off the left and right walls
    if ball_pos[0] <= ball_radius or ball_pos[0] >= (canvas_width - ball_radius):
        ball_vel[0] = -ball_vel[0]
    # Bounce off the top and bottom walls
    if ball_pos[1] <= ball_radius or ball_pos[1] >= (canvas_height - ball_radius):
        ball_vel[1] = -ball_vel[1]
    # Draw the ball
    canvas.draw_circle(ball_pos, ball_radius, 2, "Blue", "White")
# 3. Create the frame and canvas
frame = simplegui.create_frame("Bouncing Ball", canvas_width, canvas_height)
# 4. Register event handlers
frame.set_draw_handler(draw)
# 5. Start the frame
frame.start()
print("Game started! Watch the ball bounce.")

Key simpleguitk Components Explained

Component Description Example
create_frame(title, width, height) Creates the main application window. frame = simplegui.create_frame("My Game", 800, 600)
frame.set_draw_handler(draw_function) Crucial! Registers the function that will be called every frame to redraw the screen. frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown_function) Registers a function to be called when a key is pressed. frame.set_keydown_handler(key_pressed)
frame.set_mouseclick_handler(mouse_function) Registers a function to be called when the mouse is clicked. frame.set_mouseclick_handler(mouse_click)
frame.start() Starts the event loop and the application. This should be the last line. frame.start()
canvas.draw_text(text, pos, size, color) Draws text on the canvas. pos is the bottom-left corner. canvas.draw_text("Score: " + str(score), (10, 30), 24, "White")
canvas.draw_circle(center, radius, line_width, color, fill_color) Draws a circle. canvas.draw_circle(ball_pos, 20, 2, "Red", "White")
canvas.draw_polygon(point_list, line_width, color, fill_color) Draws a polygon from a list of [x, y] points. canvas.draw_polygon([[0,0], [100,0], [50,100]], 2, "Green", "Yellow")
canvas.draw_image(image, source_center, source_size, dest_center, dest_size) Draws an image. Requires loading an image first. canvas.draw_image(image, (img.get_width()/2, img.get_height()/2), (img.get_width(), img.get_height()), (pos[0], pos[1]), (50, 50))
simplegui.load_image(url) Loads an image from a URL. Returns an image object. image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/alphatest.png")
timer = simplegui.create_timer(interval, callback) Creates a timer that calls callback every interval milliseconds. timer.start()

Where to Go from Here?

simpleguitk is a perfect stepping stone. Once you're comfortable with its concepts, you can move on to more powerful and flexible libraries:

Python SimpleGUITk怎么用?-图3
(图片来源网络,侵删)
  1. Pygame: The most popular Python game development library. It gives you much more control over graphics, sound, and input handling. It's the natural next step after simpleguitk.
  2. Pyglet: Another excellent library, often considered a bit more modern and "Pythonic" than Pygame. It's great for both 2D and 3D graphics.
  3. Arcade: A modern, easy-to-use library inspired by Pygame but with a cleaner API. It's designed to be beginner-friendly while still being powerful.

Happy coding

分享:
扫描分享到社交APP
上一篇
下一篇