Как сделать меню для игры на питоне
Перейти к содержимому

Как сделать меню для игры на питоне

  • автор:

Как сделать меню для игры на питоне

Pygame is a Python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different shapes or sprites. Pygame doesn’t have an in-built layout design or any in-built UI system this means there is no easy way to make UI or levels for a game. The only way to make levels or different menus in pygame is by using functions.

Using Functions As Menus

Functions in Pygame are a way to contain different menus or levels by defining an event type in each function, then calling the functions from their respective container function.

For example, the game function will be called if the player hits the play button on the start menu. So, the start menu function becomes container functions for the game function. The important thing to note is that the start function can’t be called directly from game function. If the game contains different unlockable levels, then the previous level becomes the container function for the next level.

Create Menu Screens in Pygame (Tutorial)

Ezoic report this ad Ezoic report this ad Ezoic report this ad

Pygame is a very barebones library and offers little support for basic features required in games, such as Buttons and Menus. We could create our own Menu Screens in Pygame from scratch, but we have a much easier and better alternative called the pygame-menu library.

The Pygame-Menu library offers support for all kinds of menus, complete with many additional features like progress bars, sub-menus and prebuilt themes. Today’s tutorial will be an introduction to this library, and will teach you how to put together a simple menu in less than 30 lines of code.

We have a separate tutorial on how to create your own Button Class from Scratch in pygame, so check that out too if you are interested.

Create a simple Menu in Pygame

Before you continue with this tutorial, download the library using the following (or any equivalent) command:

Now let’s begin writing some code for our Menu. We will do a step-by-step explanation for your understanding.

First we need to make a few essential imports, and setup some basic code. If you are unfamiliar with some of the pygame concepts being used here, refer to our pygame tutorial series.

Menu Class in Pygame

The most important Class from the pygame_menu module is “Menu”. We can use this Class to create a Menu object, or even more than one. A proper menu system actually comprises of multiple menus, with one parent menu containing several submenus. A submenu can also act as a parent menu which contains a submenu(s).

The below example shows us creating two Menus. We have the mainmenu and the level menu, where the levelmenu is meant to be the submenu of mainmenu.

Each Menu can add to itself various widgets such as Buttons, Text Labels, Selectors and Progressbars, as shown above. Most of the parameters are self-explanatory.

The “button” widget takes a function name as the second parameter (which is called when the button is clicked). The “selector” widget has a parameter called onchange which takes a function name as parameter, which is called whenever we access the “selector”.

Now let’s actually define those functions that we used earlier as parameters.

The set_difficulty() and start_the_game() functions are left relatively empty. We don’t have much use for them right now. (Remember we are just making a Menu here, not the actual game).

The level_menu() function on the other hand is important because it opens the submenu “level”. If you remember, we never actually specified “level” as a submenu of Menu. However, whenever you pass a Menu into the _open() method, it becomes a submenu of the Menu to whom the _open() method belongs.

Finally at the end we run mainloop() which begins an infinite loop where our Menu is drawn and updated. This syntax is similar to the one used in Tkinter mainloop.

Code – Part#1

Now let’s combine our code and run it to see the output!

Here is the output, the “main menu” which is the first to show up. You can use both the mouse and your keyboard keys to navigate this menu.

And here is the Level Selector Menu. My clicking on the selector widget or pressing “enter” you can change the selection.

Changing our Approach

Using mainloop() to start your menu program is easy, but also has some downsides. For example, if you wish to write pygame and pygame_menu code in the same file then you cannot do so with mainloop().

This is because mainloop() starts an infinite loop, whose working we cannot modify. Hence we will change our approach a bit, and use a slightly more advanced but much better way of creating an infinite execution loop.

We will replace the following line:

As you can see, it’s 100% pygame code, and now you can begin writing pygame code inside of this infinite loop as well.

Let’s continue our Menu program a little further and show you how we can make it even better.

Creating the Loading Menu

We will be creating a new Menu called the “Loading Menu”. This menu will trigger whenever we click the “Play” button. It features a single widget, the “progressbar”, which will show the loading progress for the game.

We have also created an event for the progressbar, which will be needed to update the progressbar’s value at fixed intervals.

The pygame_menu module also comes with several “selection effects” such as the Arrow Selection widget. This gives us a nice a little arrow that hangs around the currently selected widget. We have created the arrow in the above code, and we will draw it to the window in the next section.

Modifying the Game Loop

This code section features two main parts. First we need to register the Pygame UserEvent that we just made. Just like how we deal with pygame.QUIT , we have written some code for our new event as well.

First we acquire the progressbar widget from the loading menu using the get_widget() method and the progressbar id (which we defined in the previous section). Then we use the progress bar’s built in functions to increment it’s value by 1. If it reaches a value of 100, we disable the user event by setting timer to 0.

At the end we also wrote some code to draw the “arrow” to the Menu. The get_current() method returns the currently selected Menu/submenu, and the get_selected_widget() returns the currently selected widget in that menu.

We then pass the screen object (surface) and the currently selected widget into the arrow’s draw function.

Now let’s throw all this code together.

And here is our completed Pygame Menu Screen. You should run the code yourself and navigate the menus for the best experience.

We can now see a little arrow beside the currently selected widget.

How to create a Menu in Pygame

And here is a screenshot of the progressbar during it’s loading.

This marks the end of the “Create Menu Screens in Pygame” Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Ezoic

report this ad

Создание игр на Python 3 и Pygame: Часть 4

Gigi Sayfan

Gigi Sayfan Last updated Jan 18, 2018

Russian (Pусский) translation by Marat Amerov (you can also view the original English article)

Обзор

Это четвёртая из пяти частей туториала, посвящённого созданию игр с помощью Python 3 и Pygame. В третьей части мы углубились в сердце Breakout и узнали, как обрабатывать события, познакомились с основным классом Breakout и увидели, как перемещать разные игровые объекты.

В этой части мы узнаем, как распознавать коллизии и что случается, когда мяч ударяется об разные объекты: ракетку, кирпичи, стены, потолок и пол. Наконец, мы рассмотрим важную тему пользовательского интерфейса и в частности то, как создать меню из собственных кнопок.

Распознавание коллизий

В играх объекты сталкиваются друг с другом, и Breakout не является исключением. В основном с объектами сталкивается мяч. В методе handle_ball_collisions() есть встроенная функция под названием intersect() , которая используется для проверки того, ударился ли мяч об объект, и того, где он столкнулся с объектом.Она возвращает ‘left’, ‘right’, ‘top’, ‘bottom’ или None, если мяч не столкнулся с объектом.

Столкновение мяча с ракеткой

Когда мяч стукается об ракетку, он отскакивает. Если он ударяется о верхнюю часть ракетки, то отражается обратно вверх, но сохраняет тот же компонент горизонтальной скорости.

Но если он ударяется о боковую часть ракетки, то отскакивает в противоположную сторону (влево или вправо) и продолжает движение вниз, пока не столкнётся с полом. В коде используется функция intersect().

Столкновение с полом

Когда ракетка пропускает мяч на пути вниз (или мяч ударяется об ракетку сбоку), то мяч продолжает падать и затем ударяется об пол. В этот момент игрок теряет жизнь и мяч создаётся заново, чтобы игра могла продолжаться. Игра завершается, когда у игрока заканчиваются жизни.

Столкновение с потолком и стенами

Когда мяч ударяется об стены или потолок, он просто отскакивает от них.

Столкновение с кирпичами

Когда мяч ударяется об кирпич, это является основным событием игры Breakout — кирпич исчезает, игрок получает очко, мяч отражается назад и происходят ещё несколько событий (звуковой эффект, а иногда и спецэффект), которые я рассмотрю позже.

Чтобы определить, что мяч ударился об кирпич, код проверят, пересекается ли какой-нибудь из кирпичей с мячом:

Программирование игрового меню

В большинстве игр есть какой-нибудь UI. В Breakout есть простое меню с двумя кнопками, ‘PLAY’ и ‘QUIT’. Меню отображается в начале игры и пропадает, когда игрок нажимает на ‘PLAY’. Давайте посмотрим, как реализуются кнопки и меню, а также как они интегрируются в игру.

Создание кнопок

В Pygame нет встроенной библиотеки UI. Есть сторонние расширения, но для меню я решил создать свои кнопки. Кнопка — это игровой объект, имеющий три состояния: нормальное, выделенное и нажатое. Нормальное состояние — это когда мышь не находится над кнопкой, а выделенное состояние — когда мышь находится над кнопкой, но левая кнопка мыши ещё не нажата. Нажатое состояние — это когда мышь находится над кнопкой и игрок нажал на левую кнопку мыши.

Кнопка реализуется как прямоугольник с фоновым цветом и текст, отображаемый поверх него. Также кнопка получает функцию on_click (по умолчанию являющуюся пустой лямбда-функцией), которая вызывается при нажатии кнопки.

Кнопка обрабатывает собственные события мыши и изменяет своё внутреннее состояние на основании этих событий. Когда кнопка находится в нажатом состоянии и получает событие MOUSEBUTTONUP , это означает, что игрок нажал на кнопку, и вызывается функция on_click() .

Свойство back_color , используемое для отрисовки фонового прямоугольника, всегда возвращает цвет, соответствующий текущему состоянию кнопки, чтобы игроку было ясно, что кнопка активна:

Создание меню

Функция create_menu() создаёт меню с двумя кнопками с текстом ‘PLAY’ и ‘QUIT’. Она имеет две встроенные функции, on_play() и on_quit() , которые она передаёт соответствующей кнопке. Каждая кнопка добавляется в список objects (для отрисовки), а также в поле menu_buttons .

При нажатии кнопки PLAY вызывается функция on_play(), удаляющая кнопки из списка objects , чтобы они больше не отрисовывались. Кроме того, значения булевых полей, которые запускают начало игры — is_game_running и start_level — становятся равными True.

При нажатии кнопки QUIT is_game_running принимает значение False (фактически ставя игру на паузу), а game_over присваивается значение True, что приводит к срабатыванию последовательности завершения игры.

Отображение и сокрытие игрового меню

Отображение и сокрытие меню выполняются неявным образом. Когда кнопки находятся в списке objects , меню видимо; когда они удаляются, оно скрывается. Всё очень просто.

Можно создать встроенное меню с собственной поверхностью, которое рендерит свои подкомпоненты (кнопки и другие объекты), а затем просто добавлять/удалять эти компоненты меню, но для такого простого меню это не требуется.

Подводим итог

В этой части мы рассмотрели распознавание коллизий и то, что происходит, когда мяч сталкивается с разными объектами: ракеткой, кирпичами, стенами, полом и потолком. Также мы создали меню с собственными кнопками, которое можно скрывать и отображать по команде.

В последней части серии мы рассмотрим завершение игры, отслеживание очков и жизней, звуковые эффекты и музыку.

Затем мы разработаем сложную систему спецэффектов, добавляющих в игру немного специй. Наконец, мы обсудим дальнейшее развитие и возможные улучшения.

Creating menus¶

The pygame_menu.menu.Menu is the base class to draw the graphical items on the screen. It offers many parameters to let you adapt the behavior and the visual aspects of the menu.

The less trivial ones are explained here.

Widget position¶

By default, the widgets are centered horizontally by theme, included in a virtual rectangle positioned at 0 pixel below the title bar and 0 pixel from the left border ( widget_offset=(0, 0) ).

In the same way, an offset can be defined for the title using the parameter title_offset .

The content of the menu can be centered vertically after all widgets have been added by calling the method pygame_menu.menu.Menu.center_content() :

If the menu size is insufficient to show all of the widgets, horizontal and/or vertical scrollbar(s) will appear automatically.

Column and row¶

By default, the widgets are arranged in one unique column. But using the columns and rows parameters, it is possible to arrange them in a grid.

The defined grid of columns x rows cells will be completed with the widgets (in order of definition) column by column starting at the top-left corner of the menu.

Also the width of each column can be set using column_max_width and column_min_width Menu parameters.

On-close callback¶

A callback can be defined using the onclose parameter; it will be called when the menu (end sub-menu) is closing. Closing the menu is the same as disabling it, but with callback firing.

onclose parameter can take one of these three types of values:

  • None , the menu don’t disables if pygame_menu.menu.Menu.close() is called

  • A python callable object (a function, a method) that will be called without any arguments, or with the Menu instance.

  • A specific event of pygame_menu . The possible events are the following:

    Event

    Description

    pygame_menu.events.BACK

    Go back to the previous menu and disable the current

    pygame_menu.events.CLOSE

    Only disables the current menu

    pygame_menu.events.NONE

    The same as onclose=None

    pygame_menu.events.EXIT

    Exit the program (not only the menu)

    pygame_menu.events.RESET

    Go back to the first opened menu and disable the current

Display a menu¶

The First steps chapter shows the way to display the menu, this method lets pygame-menu managing the event loop by calling the pygame_menu.menu.Menu.mainloop() :

There is a second way that gives more flexibility to the application because the events loop remains managed outside of the menu. In this case the application is in charge to update and draw the menu when it is necessary.

Menu API¶

Menu can receive many callbacks; callbacks onclose and onreset are fired (if them are callable-type). They can only receive 1 argument maximum, if so, the Menu instance is provided

Menu cannot be copied or deep-copied.

title ( str ) – Title of the Menu

width ( Union [ int , float ]) – Width of the Menu in px

height ( Union [ int , float ]) – Height of the Menu in px

center_content ( bool ) – Auto centers the Menu on the vertical position after a widget is added/deleted

column_max_width ( Union [ int , float , Tuple [ Union [ int , float ], …], List [ Union [ int , float ]], None ]) – List/Tuple representing the maximum width of each column in px, None equals no limit. For example column_max_width=500 (each column width can be 500px max), or column_max_width=(400,500) (first column 400px, second 500). If 0 uses the Menu width. This method does not resize the widgets, only determines the dynamic width of the column layout

column_min_width ( Union [ int , float , Tuple [ Union [ int , float ], …], List [ Union [ int , float ]]]) – List/Tuple representing the minimum width of each column in px. For example column_min_width=500 (each column width is 500px min), or column_max_width=(400,500) (first column 400px, second 500). Negative values are not accepted

columns ( int ) – Number of columns

enabled ( bool ) – Menu is enabled. If False the Menu cannot be drawn or updated

joystick_enabled ( bool ) – Enable/disable joystick events on the Menu

keyboard_enabled ( bool ) – Enable/disable keyboard events on the Menu

menu_id ( str ) – ID of the Menu

mouse_enabled ( bool ) – Enable/disable mouse click inside the Menu

mouse_motion_selection ( bool ) – Select widgets using mouse motion. If True menu draws a focus on the selected widget

mouse_visible ( bool ) – Set mouse visible on Menu

onclose ( Union [ MenuAction , Callable [[], Any ], Callable [[ Menu ], Any ], None ]) – Event or function executed when closing the Menu. If not None the menu disables and executes the event or function it points to. If a function (callable) is provided it can be both non-argument or single argument (Menu instance)

onreset ( Union [ Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Function executed when resetting the Menu. The function must be non-argument or single argument (Menu instance)

overflow ( Union [ Tuple [ bool , bool ], List [ bool ], bool ]) – Enables overflow on x/y axes. If False then scrollbars will not work and the maximum width/height of the scrollarea is the same as the Menu container. Style: (overflow_x, overflow_y). If False or True the value will be set on both axis

position ( Union [ Tuple [ Union [ int , float ], Union [ int , float ]], List [ Union [ int , float ]]]) – Position on x-axis and y-axis (%) respect to the window size

rows ( Union [ int , Tuple [ int , …], List [ int ], None ]) – Number of rows of each column, if there’s only 1 column None can be used for no-limit. Also a tuple can be provided for defining different number of rows for each column, for example rows=10 (each column can have a maximum 10 widgets), or rows=[2, 3, 5] (first column has 2 widgets, second 3, and third 5)

screen_dimension ( Union [ Tuple [ int , int ], List [ int ], None ]) – List/Tuple representing the dimensions the Menu should reference for sizing/positioning, if None pygame is queried for the display mode. This value defines the window_size of the Menu

theme ( Theme ) – Menu theme

touchscreen ( bool ) – Enable/disable touch action inside the Menu. Only available on pygame 2

touchscreen_motion_selection ( bool ) – Select widgets using touchscreen motion. If True menu draws a focus on the selected widget

Centers the content of the Menu vertically. This action rewrites widget_offset .

If the height of the widgets is greater than the height of the Menu, the drawing region will cover all Menu inner surface.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Clears all widgets.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

reset ( bool ) – If True the menu full-resets

Closes the current Menu firing onclose callback. If callback=None this method does nothing.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().reset(. ) .

True if the Menu has executed the onclose callback

Check if user event collides the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

event ( Event ) – Pygame event

True if collide

Disables the Menu (doesn’t check events and draw on the surface).

This method does not fires onclose callback. Use Menu.close() instead.

draw ( surface , clear_surface = False ) [source] ¶

Draw the current Menu into the given surface.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().draw(. )

surface ( Surface ) – Pygame surface to draw the Menu

clear_surface ( bool ) – Clear surface using theme default color

Self reference (current)

Enables Menu (can check events and draw).

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Forces current Menu surface cache to update after next drawing call.

This method only updates the surface cache, without forcing re-rendering of all Menu widgets.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().update(. ) .

Forces current Menu surface update after next rendering call.

This method is expensive, as menu surface update forces re-rendering of all widgets (because them can change in size, position, etc…).

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().update(. ) .

Reset the Menu back to the first opened Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Return the pygame Menu timer.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Pygame clock object

Get the current active Menu. If the user has not opened any submenu the pointer object must be the same as the base. If not, this will return the opened Menu pointer.

Menu object (current)

Return the Menu decorator API.

prev menu decorator may not draw because pygame_menu.widgets.MenuBar and pygame_menu._scrollarea.ScrollArea objects draw over it. If it’s desired to draw a decorator behind widgets, use the ScrollArea decorator, for example: menu.get_scrollarea().get_decorator() .

The menu drawing order is:

Menu background color/image

Menu prev decorator

Menu ScrollArea prev decorator

Menu ScrollArea widgets

Menu ScrollArea post decorator

Menu post decorator

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

get_height ( inner = False , widget = False ) [source] ¶

Get the Menu height.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

inner ( bool ) – If True returns the available height (menu height minus scroll and menubar)

widget ( bool ) – If True returns the total height used by the widgets

Get selected widget index from the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Selected widget index

get_input_data ( recursive = False ) [source] ¶

Return input data from a Menu. The results are given as a dict object. The keys are the ID of each element.

With recursive=True it collect also data inside the all sub-menus.

This is applied only to the base Menu (not the currently displayed), for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

recursive ( bool ) – Look in Menu and sub-menus

Return menubar widget.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

get_mouseover_widget ( filter_appended = True ) [source] ¶

Return the mouseover widget on the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

filter_appended ( bool ) – If True return the widget only if it’s appended to the base Menu

Widget object, None if no widget is mouseover

Return the menu position (constructor + translation).

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Position on x-axis and y-axis (x,y) in px

Return the pygame.Rect object of the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Return the Menu ScrollArea.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Return the selected widget on the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Widget object, None if no widget is selected

get_size ( inner = False , widget = False ) [source] ¶

Return the Menu size as a tuple of (width, height) in px.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

inner ( bool ) – If True returns the available (width, height) (menu height minus scroll and menubar)

widget ( bool ) – If True returns the total (width, height) used by the widgets

Tuple of (width, height) in px

Return the Menu sound engine.

Return the Menu theme.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Use with caution, changing the theme may affect other menus or widgets if not properly copied.

Return the title of the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Get Menu translate on x-axis and y-axis (x, y) in px.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Translation on both axis

get_widget ( widget_id , recursive = False ) [source] ¶

Return a widget by a given ID from the Menu.

With recursive=True it looks for a widget in the Menu and all sub-menus.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

None is returned if no widget is found.

widget_id ( str ) – Widget ID

recursive ( bool ) – Look in Menu and submenus

Return the Menu widgets as a tuple.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

get_width ( inner = False , widget = False ) [source] ¶

Get the Menu width.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

inner ( bool ) – If True returns the available width (menu width minus scroll if visible)

widget ( bool ) – If True returns the total width used by the widgets

Return the window size as a tuple of (width, height).

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Window size in px

in_submenu ( menu , recursive = False ) [source] ¶

Return True if menu is a submenu of the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

menu ( Menu ) – Menu to check

recursive ( bool ) – Check recursively

True if menu is in the submenus

Return True if the Menu is enabled.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Menu enabled status

Main loop of the current Menu. In this function, the Menu handle exceptions and draw. The Menu pauses the application and checks pygame events itself.

This method returns until the Menu is updated (a widget status has changed).

The execution of the mainloop is at the current Menu level.

The bgfun callable (if not None) can receive 1 argument maximum, if so, the Menu instance is provided:

clear_surface (bool) – If True surface is cleared using theme.surface_clear_color

disable_loop (bool) – If True the mainloop only runs once. Use for running draw and update in a single call

fps_limit (int) – Maximum FPS of the loop. Default equals to theme.fps . If 0 there’s no limit

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().mainloop(. ) .

surface ( Surface ) – Pygame surface to draw the Menu

bgfun ( Union [ Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Background function called on each loop iteration before drawing the Menu

kwargs – Optional keyword arguments

Self reference (current)

move_widget_index ( widget , index = None , render = True , ** kwargs ) [source] ¶

Move a given widget to a certain index. index can be another widget, a numerical position, or None ; if None the widget is pushed to the last widget list position.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

widget ( Optional [ Widget ]) – Widget to move. If None the widgets are flipped or reversed and returns None

index ( Union [ Widget , int , None ]) – Target index. It can be a widget, a numerical index, or None ; if None the widget is pushed to the last position

render ( bool ) – Force menu rendering after update

kwargs – Optional keyword arguments

The new indices of the widget and the previous index element

Remove the widget from the Menu. If widget not exists on Menu this method raises a ValueError exception.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

widget ( Union [ Widget , str ]) – Widget object or Widget ID

Force the current Menu to render. Useful to force widget update.

This method should not be called if the Menu is being drawn as this method is called by pygame_menu.menu.Menu.draw()

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().render(. )

Self reference (current)

Go back in Menu history a certain number of times from the current Menu. This method operates through the current Menu pointer.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().reset(. ) .

total ( int ) – How many menus to go back

Self reference (current)

reset_value ( recursive = False ) [source] ¶

Reset all widget values to default.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

recursive ( bool ) – Set value recursively

scroll_to_widget ( widget , scroll_parent = True ) [source] ¶

Scroll the Menu to the given widget.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

widget ( Optional [ Widget ]) – Widget to request scroll. If None scrolls to the selected widget

scroll_parent ( bool ) – If True parent scroll also scrolls to rect

Select a widget from the Menu. If None unselect the current one.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

widget ( Union [ Widget , str , None ]) – Widget to be selected or Widget ID. If None unselect the current

Set onbeforeopen callback. Callback is executed before opening the Menu, it receives the current Menu and the next Menu:

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

onbeforeopen ( Optional [ Callable [[ Menu , Menu ], Any ]]) – Onbeforeopen callback, it can be a function or None

Set onclose callback. Callback can only receive 1 argument maximum (if not None ), if so, the Menu instance is provided:

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

onclose ( Union [ MenuAction , Callable [[], Any ], Callable [[ Menu ], Any ], None ]) – Onclose callback, it can be a function, a pygame-menu event, or None

Set onmouseleave callback. This method is executed in pygame_menu.menu.Menu.update() method. The callback function receives the following arguments:

onmouseleave ( Optional [ Callable [[ Menu , Event ], Any ]]) – Callback executed if user leaves the Menu with the mouse; it can be a function or None

Set onmouseover callback. This method is executed in pygame_menu.menu.Menu.update() method. The callback function receives the following arguments:

onmouseover ( Optional [ Callable [[ Menu , Event ], Any ]]) – Callback executed if user enters the Menu with the mouse; it can be a function or None

Set onreset callback. Callback can only receive 1 argument maximum (if not None ), if so, the Menu instance is provided:

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

onreset ( Union [ Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Onreset callback, it can be a function or None

Set onupdate callback. Callback is executed before updating the Menu, it receives the event list and the menu reference:

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

onupdate ( Optional [ Callable [[ List [ Event ], Menu ], Any ]]) – Onupdate callback, it can be a function or None

Set onmouseleave callback. This method is executed in pygame_menu.menu.Menu.update() method. The callback function receives the following arguments:

onwindowmouseleave ( Optional [ Callable [[ Menu ], Any ]]) – Callback executed if user leaves the window with the mouse; it can be a function or None

Set onwindowmouseover callback. This method is executed in pygame_menu.menu.Menu.update() method. The callback function receives the following arguments:

onwindowmouseover ( Optional [ Callable [[ Menu ], Any ]]) – Callback executed if user enters the window with the mouse; it can be a function or None

set_relative_position ( position_x , position_y ) [source] ¶

Set the Menu position relative to the window.

Menu left position (x) must be between 0 and 100 , if 0 the margin is at the left of the window, if 100 the Menu is at the right of the window.

Menu top position (y) must be between 0 and 100 , if 0 the margin is at the top of the window, if 100 the margin is at the bottom of the window.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

position_x ( Union [ int , float ]) – Left position of the window

position_y ( Union [ int , float ]) – Top position of the window

set_sound ( sound , recursive = False ) [source] ¶

Add a sound engine to the Menu. If recursive=True , the sound is applied to all submenus.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

sound ( Optional [ Sound ]) – Sound object

recursive ( bool ) – Set the sound engine to all submenus

Set the title of the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

title ( Any ) – New menu title

offset ( Union [ Tuple [ Union [ int , float ], Union [ int , float ]], List [ Union [ int , float ]], None ]) – If None uses theme offset, else it defines the title offset on x-axis and y-axis (x, y)

Switch between enable/disable Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Translate to (+x, +y) according to the default position.

To revert changes, only set to (0, 0) .

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

x ( Union [ int , float ]) – +X in px

y ( Union [ int , float ]) – +Y in px

Update the status of the Menu using external events. The update event is applied only on the current Menu.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().update(. ) .

events ( Union [ List [ Event ], Tuple [ Event ]]) – Pygame events as a list

True if mainloop must be stopped

© Copyright Copyright 2017-2021 Pablo Pizarro R. @ppizarror. Revision 1401d462 .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *