Pygame Lesson 1: Creating a Window

Life is short, I use Python!

Table of contents

1. Installation of Pygame library

2. Formal explanation

2.1 Start function

2.2 Create window

2.3 Modify name

3. Eliminate errors

NameError: name 'pygame' is not defined

TypeError: size must be two numbers

TypeError: function takes at least 1 argument (0 given)


1. Installation of Pygame library

First, we press the Win+R keys, enter cmd, and press Enter.

Then, enter"python -m pip install -U pygame --user",and press Enter to install .

When the progress bar finally reaches 100%, the installation is completed.

2. Formal explanation

2.1 Start function

The method is very simple, it is the init() function.

Example:

import pygame  #导入pygame
pygame.init()

2.2 Create window

After pygame.init(), a window must be created. This is the pyame.display.set_mode() method.

The syntax is:

pygame.display.set_mode([width,height])

Note: It is often necessary to save it in a variable for easy calling.

Example:

import pygame  #导入pygame

pygame.init()
screen=pygame.display.set_mode([1500,1000])  #创建一个宽1500像素,高1000像素的Surface对象,命名为screen

2.3 Modify name

If you need to change the window name, you need the pygame.display.set_caption() method.

Its parameter is of str type (A string enclosed in double quotes).

Example:

import pygame  #导入pygame

pygame.init()
screen=pygame.display.set_mode([1500,1000])  #创建一个宽1500像素,高1000像素的Surface对象,命名为screen

pygame.display.set_caption("我的pyame窗口")   #命名窗口为“我的pygame”窗口

3. Eliminate errors

NameError: name 'pygame' is not defined

This error is very simple. The reason is that you forgot to import the pygame library. Just add import pygame in the first line.

TypeError: size must be two numbers

This error, translated, is:The size must be two numbers.

You need to find the pygame.display.set_mode() function,Enlarge the two numbers with "()" or "[ ]".

TypeError: function takes at least 1 argument (0 given)

This error, the translation is:This function takes at least 1 parameter (0 parameters are passed).

Just complete the parameters.

Guess you like

Origin blog.csdn.net/Python_program/article/details/132940612