Making buttons in python
Одним из наиболее используемых компонентов в графических программах является кнопка. В tkinter кнопки представлены классом Button . Основные параметры виджета Button:
- command : функция, которая вызывается при нажатии на кнопку
- compund : устанавливает расположение картинки и текста относительно друг друга
- cursor : курсор указателя мыши при наведении на метку
- image : ссылка на изображение, которое отображается на метке
- pading : отступы от границ вилжета до его текста
- state : состояние кнопки
- text : устанавливает текст метки
- textvariable : устанавливает привязку к элементу StringVar
- underline : указывает на номер символа в тексте кнопки, который подчеркивается. По умолчанию значение -1, то есть никакой символ не подчеркивается
- width : ширина виджета
Добавим в окно обычную кнопку из пакета ttk:
from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") # стандартная кнопка btn = ttk.Button(text="Button") btn.pack() root.mainloop()
Для создания кнопки используется конструктор Button() . В этом конструкторе с помощью параметра text можно установить текст кнопки.
Чтобы разместить виджет в контейнере (главном окне), у него вызывается метод pack() . На ОС Windows мы получим следующую кнопку:
Конструктор Button определяет различные параметры, которые позволяют настроить поведение и внешний вид кнопки. Однако конкретный набор параметров зависит от того, используем ли мы кнопки из пакета tkinter или из пакета tkinter.ttk.
Обработка нажатия на кнопку
Для обработки нажатия на кнопку необходимо установить в конструкторе параметр command , присвоив ему ссылку на функцию, которая будет срабатывать при нажатии:
from tkinter import * from tkinter import ttk clicks = 0 def click_button(): global clicks clicks += 1 # изменяем текст на кнопке btn["text"] = f"Clicks " root = Tk() root.title("METANIT.COM") root.geometry("250x150") btn = ttk.Button(text="Click Me", command=click_button) btn.pack() root.mainloop()
Здесь в качестве обработчика нажатия устанавливается функция click_button. В этой функции изменяется глобальная переменная clicks, которая хранит число кликов. Кроме того, изменяем текст кнопки, чтобы визуально было видно сколько нажатий произведено. Таким образом, при каждом нажатии кнопки будет срабатывать функция click_button, и количество кликов будет увеличиваться:
Отключение кнопки
Для ttk-кнопки мы можем установить отключенное состояние с помощью метода state() , передав ему значение «disabled». С такой кнопкой пользователь не сможет взаимодействовать:
from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") btn = ttk.Button(text="Click Me", state=["disabled"]) btn.pack() root.mainloop()
При этом в метод state мы можем передать набор состояний, поэтому значение «disabled» передается внутри списка.
Making buttons in python
- Python | Creating a button in tkinter
- Python | Add style to tkinter button
- Python | Add image on a Tkinter button
- Python Tkinter – Label
- Python Tkinter | Create LabelFrame and add widgets to it
- RadioButton in Tkinter | Python
- Python Tkinter – Checkbutton Widget
- Python Tkinter – Canvas Widget
- Python Tkinter | Create different shapes using Canvas class
- Python Tkinter | Create different type of lines using Canvas class
- Python Tkinter | Moving objects using Canvas.move() method
- Combobox Widget in tkinter | Python
- maxsize() method in Tkinter | Python
- minsize() method in Tkinter | Python
- resizable() method in Tkinter | Python
- Python Tkinter – Entry Widget
- Tkinter – Read only Entry Widget
- Python Tkinter – Text Widget
- Python Tkinter – Message
- Python | Menu widget in Tkinter
- Python Tkinter – Menubutton Widget
- Python Tkinter – SpinBox
- Progressbar widget in Tkinter | Python
- Python-Tkinter Scrollbar
- Python Tkinter – ScrolledText Widget
- Python Tkinter – ListBox Widget
- Scrollable ListBox in Python-tkinter
- Python Tkinter – Frame Widget
- Scrollable Frames in Tkinter
- How to make a proper double scrollbar frame in Tkinter
- Python Tkinter – Scale Widget
- Hierarchical treeview in Python GUI application
- Python-Tkinter Treeview scrollbar
- Python Tkinter – Toplevel Widget
- Python | askopenfile() function in Tkinter
- Python | asksaveasfile() function in Tkinter
- Python – Tkinter askquestion Dialog
- Python Tkinter – MessageBox Widget
- Create a Yes/No Message Box in Python using tkinter
- Change the size of MessageBox – Tkinter
- Different messages in Tkinter | Python
- Change Icon for Tkinter MessageBox
- Python – Tkinter Choose color Dialog
- Popup Menu in Tkinter
- Getting screen’s height and width using Tkinter | Python
- Python | How to dynamically change text of Checkbutton
- Python | focus_set() and focus_get() method
- Search String in Text using Python-Tkinter
- Autocomplete ComboBox in Python-Tkinter
- Autohiding Scrollbars using Python-tkinter
- Python Tkinter – Validating Entry Widget
- Tracing Tkinter variables in Python
- Python | setting and retrieving values of Tkinter variable
- Tkinter | Adding style to the input text using ttk.Entry widget
- Python | after method in Tkinter
- destroy() method in Tkinter | Python
- Text detection using Python
- Python | winfo_ismapped() and winfo_exists() in Tkinter
- Collapsible Pane in Tkinter | Python
- Creating a multiple Selection using Tkinter
- Creating Tabbed Widget With Python-Tkinter
- Open a new Window with a button in Python-Tkinter
- Cryptography GUI using python
- Python | Simple GUI calculator using Tkinter
- Create Table Using Tkinter
- Python | GUI Calendar using Tkinter
- File Explorer in Python using Tkinter
- Python | ToDo GUI Application using Tkinter
- Python: Weight Conversion GUI using Tkinter
- Python: Age Calculator using Tkinter
- Python | Create a GUI Marksheet using Tkinter
- Python | Loan calculator using Tkinter
- Python | Create a digital clock using Tkinter
- Make Notepad using Tkinter
- Color game using Tkinter in Python
- Python | Simple FLAMES game using Tkinter
- Simple registration form using Python Tkinter
- How to create a COVID19 Data Representation GUI?
- Python | Creating a button in tkinter
- Python | Add style to tkinter button
- Python | Add image on a Tkinter button
- Python Tkinter – Label
- Python Tkinter | Create LabelFrame and add widgets to it
- RadioButton in Tkinter | Python
- Python Tkinter – Checkbutton Widget
- Python Tkinter – Canvas Widget
- Python Tkinter | Create different shapes using Canvas class
- Python Tkinter | Create different type of lines using Canvas class
- Python Tkinter | Moving objects using Canvas.move() method
- Combobox Widget in tkinter | Python
- maxsize() method in Tkinter | Python
- minsize() method in Tkinter | Python
- resizable() method in Tkinter | Python
- Python Tkinter – Entry Widget
- Tkinter – Read only Entry Widget
- Python Tkinter – Text Widget
- Python Tkinter – Message
- Python | Menu widget in Tkinter
- Python Tkinter – Menubutton Widget
- Python Tkinter – SpinBox
- Progressbar widget in Tkinter | Python
- Python-Tkinter Scrollbar
- Python Tkinter – ScrolledText Widget
- Python Tkinter – ListBox Widget
- Scrollable ListBox in Python-tkinter
- Python Tkinter – Frame Widget
- Scrollable Frames in Tkinter
- How to make a proper double scrollbar frame in Tkinter
- Python Tkinter – Scale Widget
- Hierarchical treeview in Python GUI application
- Python-Tkinter Treeview scrollbar
- Python Tkinter – Toplevel Widget
- Python | askopenfile() function in Tkinter
- Python | asksaveasfile() function in Tkinter
- Python – Tkinter askquestion Dialog
- Python Tkinter – MessageBox Widget
- Create a Yes/No Message Box in Python using tkinter
- Change the size of MessageBox – Tkinter
- Different messages in Tkinter | Python
- Change Icon for Tkinter MessageBox
- Python – Tkinter Choose color Dialog
- Popup Menu in Tkinter
- Getting screen’s height and width using Tkinter | Python
- Python | How to dynamically change text of Checkbutton
- Python | focus_set() and focus_get() method
- Search String in Text using Python-Tkinter
- Autocomplete ComboBox in Python-Tkinter
- Autohiding Scrollbars using Python-tkinter
- Python Tkinter – Validating Entry Widget
- Tracing Tkinter variables in Python
- Python | setting and retrieving values of Tkinter variable
- Tkinter | Adding style to the input text using ttk.Entry widget
- Python | after method in Tkinter
- destroy() method in Tkinter | Python
- Text detection using Python
- Python | winfo_ismapped() and winfo_exists() in Tkinter
- Collapsible Pane in Tkinter | Python
- Creating a multiple Selection using Tkinter
- Creating Tabbed Widget With Python-Tkinter
- Open a new Window with a button in Python-Tkinter
- Cryptography GUI using python
- Python | Simple GUI calculator using Tkinter
- Create Table Using Tkinter
- Python | GUI Calendar using Tkinter
- File Explorer in Python using Tkinter
- Python | ToDo GUI Application using Tkinter
- Python: Weight Conversion GUI using Tkinter
- Python: Age Calculator using Tkinter
- Python | Create a GUI Marksheet using Tkinter
- Python | Loan calculator using Tkinter
- Python | Create a digital clock using Tkinter
- Make Notepad using Tkinter
- Color game using Tkinter in Python
- Python | Simple FLAMES game using Tkinter
- Simple registration form using Python Tkinter
- How to create a COVID19 Data Representation GUI?
How to make buttons in python/pygame?
I’m making a game in pygame and on the first screen I want there to be buttons that you can press to (i) start the game, (ii) load a new screen with instructions, and (iii) exit the program. I’ve found this code online for button making, but I don’t really understand it (I’m not that good at object oriented programming). If I could get some explanation as to what it’s doing that would be great. Also, when I use it and try to open a file on my computer using the file path, I get the error sh: filepath :Permission denied, which I don’t know how to solve.
#load_image is used in most pygame programs for loading images def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() class Button(pygame.sprite.Sprite): """Class used to create a button, use setCords to set position of topleft corner. Method pressed() returns a boolean and should be called inside the input loop.""" def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('button.png', -1) def setCords(self,x,y): self.rect.topleft = x,y def pressed(self,mouse): if mouse[0] > self.rect.topleft[0]: if mouse[1] > self.rect.topleft[1]: if mouse[0] < self.rect.bottomright[0]: if mouse[1] < self.rect.bottomright[1]: return True else: return False else: return False else: return False else: return False def main(): button = Button() #Button class is created button.setCords(200,200) #Button is displayed at 200,200 while 1: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: mouse = pygame.mouse.get_pos() if button.pressed(mouse): #Button's pressed method is called print ('button hit') if __name__ == '__main__': main()
6 Answers 6
I don't have a code example for you, but how I would do it is to:
- Make a Button class, with the text to go on the button as a constructor argument
- Create a PyGame surface, either of an image or filled Rect
- Render text on it with the Font.Render stuff in Pygame
That is similar to what your example is doing, although different still.
Another good way to create buttons on pygame (in Python) is by installing the package called pygame_widgets ( pip3 install pygame_widgets ).
# Importing modules import pygame as pg import pygame_widgets as pw # Creating screen pg.init() screen = pg.display.set_mode((800, 600)) running = True button = pw.Button( screen, 100, 100, 300, 150, text='Hello', fontSize=50, margin=20, inactiveColour=(255, 0, 0), pressedColour=(0, 255, 0), radius=20, onClick=lambda: print('Click') )
events = pg.event.get() for event in events: if event.type == pg.QUIT: running = False button.listen(events) button.draw() pg.display.update()