С Новым годом! Форум программистов, компьютерный форум, киберфорум
Python: PyGame
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.93/29: Рейтинг темы: голосов - 29, средняя оценка - 4.93
0 / 0 / 0
Регистрация: 19.05.2020
Сообщений: 9

При нажатии кнопки PyQt5 открыть окно PyGame

05.01.2021, 19:11. Показов 5670. Ответов 5

Студворк — интернет-сервис помощи студентам
Здравствуйте, возможно ли при нажатии на кнопку PyQt5 открыть окно PyGame?

это первая форма, на которой при нажатии кнопки играть открывается форма, в которой нужно открыть окно PyGame
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import sys
 
 
from PyQt5.QtWidgets import QApplication, QMainWindow
from main import Ui_MainWindow
 
from program_for_play import MyWidget2
 
 
class MyWidget(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.dialog2 = MyWidget2()
        self.setupUi(self)
        self.play_btn.clicked.connect(self.showDialog2)
        self.pushButton_4.clicked.connect(self.showDialog1)
        self.time_btn.clicked.connect(self.showDialog3)
 
    def showDialog2(self):
        self.dialog2.show()
 
 
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyWidget()
    ex.show()
    sys.exit(app.exec_())

Это интерфейс для нее
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from PyQt5 import QtCore, QtGui, QtWidgets
 
 
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(455, 382)
        MainWindow.setStyleSheet("background-color: rgb(240, 248, 255);")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(120, 30, 237, 77))
        font = QtGui.QFont()
        font.setPointSize(48)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setStyleSheet("color: rgb(0, 100, 100);")
        self.label.setObjectName("label")
        self.play_btn = QtWidgets.QPushButton(self.centralwidget)
        self.play_btn.setGeometry(QtCore.QRect(104, 150, 271, 41))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.play_btn.setFont(font)
        self.play_btn.setStyleSheet("background-color: rgb(220, 220, 220);\n"
"color: rgb(0, 100, 100);")
        self.play_btn.setObjectName("play_btn")
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(100, 210, 271, 41))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setStyleSheet("background-color: rgb(220, 220, 220);\n"
"color: rgb(0, 100, 100);")
        self.pushButton_4.setObjectName("pushButton_4")
        self.time_btn = QtWidgets.QPushButton(self.centralwidget)
        self.time_btn.setGeometry(QtCore.QRect(100, 270, 271, 41))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.time_btn.setFont(font)
        self.time_btn.setStyleSheet("background-color: rgb(220, 220, 220);\n"
"color: rgb(0, 100, 100);")
        self.time_btn.setObjectName("time_btn")
        MainWindow.setCentralWidget(self.centralwidget)
 
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
 
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "Судоку"))
        self.play_btn.setText(_translate("MainWindow", "Играть"))
        self.pushButton_4.setText(_translate("MainWindow", "Правила"))
        self.time_btn.setText(_translate("MainWindow", "Статистика"))

это открывающаяся форма
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import sys
import pygame
 
 
from PyQt5.QtWidgets import QApplication, QMainWindow
from play import Ui_MainWindow1
 
 
 
class MyWidget2(QMainWindow, Ui_MainWindow1):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
# открыть окно pygame        self.easy_btn.clicked.connect 
 
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyWidget2()
    ex.show()
    sys.exit(app.exec_())
Это ее интерфейс
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from PyQt5 import QtCore, QtGui, QtWidgets
 
 
class Ui_MainWindow1(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(445, 368)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(120, 30, 237, 77))
        font = QtGui.QFont()
        font.setPointSize(48)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setStyleSheet("color: rgb(0, 100, 100);")
        self.label.setObjectName("label")
        self.easy_btn = QtWidgets.QPushButton(self.centralwidget)
        self.easy_btn.setGeometry(QtCore.QRect(100, 130, 271, 41))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.easy_btn.setFont(font)
        self.easy_btn.setStyleSheet("background-color: rgb(220, 220, 220);\n"
"color: rgb(0, 100, 100);")
        self.easy_btn.setObjectName("easy_btn")
        self.medium_btn = QtWidgets.QPushButton(self.centralwidget)
        self.medium_btn.setGeometry(QtCore.QRect(100, 200, 271, 41))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.medium_btn.setFont(font)
        self.medium_btn.setStyleSheet("background-color: rgb(220, 220, 220);\n"
"color: rgb(0, 100, 100);")
        self.medium_btn.setObjectName("medium_btn")
        self.play_btn_3 = QtWidgets.QPushButton(self.centralwidget)
        self.play_btn_3.setGeometry(QtCore.QRect(100, 270, 271, 41))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.play_btn_3.setFont(font)
        self.play_btn_3.setStyleSheet("background-color: rgb(220, 220, 220);\n"
"color: rgb(0, 100, 100);")
        self.play_btn_3.setObjectName("play_btn_3")
        MainWindow.setCentralWidget(self.centralwidget)
 
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
 
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "Играть"))
        self.easy_btn.setText(_translate("MainWindow", "Легко"))
        self.medium_btn.setText(_translate("MainWindow", "Средне"))
        self.play_btn_3.setText(_translate("MainWindow", "Сложно"))
А это окно pygame
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import pygame
 
if __name__ == '__main__':
    pygame.init()
    size = width, height = 800, 400
    screen = pygame.display.set_mode(size)
    x_pos = 15
    v = 10
    clock = pygame.time.Clock()
    running = True
    x = 1
    while running:
        screen.fill([0, 0, 255])
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                x = event.pos
                x_pos = 0
        if x != 1:
            pygame.draw.circle(screen, (255, 255, 0), x, x_pos)
            x_pos += v * clock.tick() / 1000
        pygame.display.update()
    pygame.quit()
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
05.01.2021, 19:11
Ответы с готовыми решениями:

Открыть новое окно при нажатии кнопки
Вот есть у меня начальное окно. На котором у меня есть кнопка, у которой есть слушатель public class Labaa2 extends JFrame { ...

Открыть новое окно при нажатии кнопки
Проблема следующая. Есть два класса - Entry и ClientGUI, и при нажатии кнопки ОК в Entry нужно открыть окно ClientGUI. При этом первое окно...

Как открыть новое окно при нажатии кнопки?
U menja na forme Button. Podskazite, kak otkrit novoe okno pri nazatie na knopku? Spasibo Inessa

5
963 / 718 / 276
Регистрация: 10.12.2016
Сообщений: 1,762
05.01.2021, 19:48
можно
https://github.com/mrexodia/pygame_qt
только зачем?
1
0 / 0 / 0
Регистрация: 19.05.2020
Сообщений: 9
05.01.2021, 21:45  [ТС]
да так, для проекта нужно
Спасибо

Добавлено через 18 минут
Что-то я запуталась, не получается
Не могли бы вы помочь?

открывается лишь черное окно pygame(
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import sys
import pygame
 
 
#импортирую программу с графическим интерфейсом, сделанном в QtDesigner 
from PyQt5.QtWidgets import QApplication, QMainWindow
from play import Ui_MainWindow1
 
class Game():
    def __init__(self):
        pygame.init()
        self.game_init()
 
    def game_init(self):
        size = width, height = 800, 400
        screen = pygame.display.set_mode(size)
        self.x_pos = 15
        self.v = 10
        self.clock = pygame.time.Clock()
 
    def loop(self, MyWidget2):
        running = True
        x = 1
        while running:
            screen.fill([0, 0, 255])
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x = event.pos
                    x_pos = 0
            if x != 1:
                pygame.draw.circle(screen, (255, 255, 0), x, x_pos)
                x_pos += v * clock.tick() / 1000
            pygame.display.update()
        pygame.quit()
 
 
# Наследуется от виджета из PyQt5.QtWidgets и от класса с интерфейсом
class MyWidget2(QMainWindow, Ui_MainWindow1):
    def __init__(self, game):
        super().__init__()
        self.setupUi(self)
        self.game = game
        self.init_pygame(game)
 
    def init_pygame(self, game):
        self.game = game
        self.easy_btn.clicked.connect(self.openGame)
 
    def openGame(self):
        if self.game.loop(self):
            self.close()
 
 
def main():
    game = Game()
    app = QApplication(sys.argv)
    ex = MyWidget2(game)
    result = app.exec_()
    sys.exit(result)
 
if __name__ == "__main__":
    main()
0
963 / 718 / 276
Регистрация: 10.12.2016
Сообщений: 1,762
05.01.2021, 22:47
вы не используете QTimer
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import sys, time
 
import pygame
 
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QTimer
 
# https://www.pygame.org/docs/tut/PygameIntro.html
class Game():
    def __init__(self):
        pygame.init()
        self.game_init()
 
    # pygame initialization
    def game_init(self):
        self.size = self.width, self.height = 320, 240
        self.speed = [2, 2]
        self.black = 0, 0, 0
        self.screen = pygame.display.set_mode(self.size)
        self.ball = pygame.image.load("ball.gif")
        self.ballrect = self.ball.get_rect()
 
    # pygame main loop
    def loop(self, window):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return True
 
        self.ballrect = self.ballrect.move(self.speed)
        if self.ballrect.left < 0 or self.ballrect.right > self.width:
            self.speed[0] = -self.speed[0]
        if self.ballrect.top < 0 or self.ballrect.bottom > self.height:
            self.speed[1] = -self.speed[1]
 
        self.screen.fill(self.black)
        self.screen.blit(self.ball, self.ballrect)
        pygame.display.flip()
        return False
 
# https://pythonspot.com/en/pyqt5-buttons
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 simple window - pythonspot.com'
        self.left = 10
        self.top = 10
        self.width = 300
        self.height = 200
        self.init_ui()
        
 
    def init_ui(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.button = QPushButton('Click', self)
        self.button.move(100, 70)
        self.button.clicked.connect(self.on_click)
        self.show()
 
    def init_pygame(self):
        # https://stackoverflow.com/questions/46656634/pyqt5-qtimer-count-until-specific-seconds
        self.game = Game()
        self.timer = QTimer()
        self.timer.timeout.connect(self.pygame_loop)
        self.timer.start(20)
 
    def pygame_loop(self):
        if self.game.loop(self):
            pygame.quit()
 
    def on_click(self):
        self.init_pygame()
 
 
def main():
    app = QApplication(sys.argv)
    ex = Window()
    result = app.exec_()
    sys.exit(result)
 
if __name__ == "__main__":
    main()
Добавлено через 8 минут
чтобы Qt не закрывалось
Python
1
2
3
4
5
    def pygame_loop(self):
        if self.game.loop(self):
            self.timer.stop()
            self.timer.disconnect()
            pygame.quit()
1
0 / 0 / 0
Регистрация: 19.05.2020
Сообщений: 9
09.01.2021, 12:34  [ТС]
У меня открывается окно, но, когда я нажимаю на кнопку, оно закрывается и завершает работу. В чем может быть ошибка?

Вот код
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import sys, time
import pygame
 
 
#импортирую программу с графическим интерфейсом, сделанном в QtDesigner 
from PyQt5.QtWidgets import QApplication, QMainWindow
from play import Ui_MainWindow1
from PyQt5.QtCore import QTimer
 
class Game():
    def __init__(self):
        pygame.init()
        self.game_init()
 
    def game_init(self):
        size = width, height = 800, 400
        screen = pygame.display.set_mode(size)
        self.x_pos = 15
        self.v = 10
 
    def loop(self, MyWidget2):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return True
        running = True
        x = 1
        while running:
            screen.fill([0, 0, 255])
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x = event.pos
                    x_pos = 0
            if x != 1:
                pygame.draw.circle(screen, (255, 255, 0), x, x_pos)
                x_pos += v * clock.tick() / 1000
            pygame.display.update()
        return False
 
 
# Наследуется от виджета из PyQt5.QtWidgets и от класса с интерфейсом
class MyWidget2(QMainWindow, Ui_MainWindow1):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.init_ui()
 
    def init_ui(self):
        self.easy_btn.clicked.connect(self.openGame)
        self.show()
 
    def init_pygame(self, game):
        self.game = Game
        self.timer = QTimer()
        self.timer.timeout.connect(self.pygame_loop)
        self.timer.start(20)
 
    def pygame_loop(self):
        if self.game.loop(self):
            self.timer.stop()
            self.timer.disconnect()
            pygame.quit()
 
    def openGame(self):
        self.init_pygame()
 
 
def main():
    app = QApplication(sys.argv)
    ex = MyWidget2()
    result = app.exec_()
    sys.exit(result)
 
if __name__ == "__main__":
    main()
0
963 / 718 / 276
Регистрация: 10.12.2016
Сообщений: 1,762
09.01.2021, 20:37
Лучший ответ Сообщение было отмечено kkkkatiko как решение

Решение

проще сказать где у вас ошибок нет
у Qt свой eventloop, у pygame свой
чтоб их совместить QTimer и нужен
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import sys
import pygame
 
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import QTimer
 
class Game():
    def __init__(self):
        pygame.init()
        self.game_init()
 
    def game_init(self):
        size = width, height = 600, 400
        self.screen = pygame.display.set_mode(size)
        self.x_pos = 15
        self.v = 10
        self.x = 1
        self.clock = pygame.time.Clock()
 
    def loop(self, window):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return True
            if event.type == pygame.MOUSEBUTTONDOWN:
                self.x = event.pos
                self.x_pos = 0
        self.screen.fill([0, 0, 255])
        if self.x != 1:
            pygame.draw.circle(self.screen, (255, 255, 0), self.x, self.x_pos)
            self.x_pos += self.v * self.clock.tick()/1000
        pygame.display.update()
        return False
 
class MyWidget2(QWidget):
    def __init__(self):
        super().__init__()
        self.btn = QPushButton('Play',self)
        self.init_ui()
 
    def init_ui(self):
        self.btn.clicked.connect(self.openGame)
        self.show()
 
    def init_pygame(self):
        self.game = Game()
        self.timer = QTimer()
        self.timer.timeout.connect(self.pygame_loop)
        self.timer.start(10)
 
    def pygame_loop(self):
        if self.game.loop(self):
            self.timer.stop()
            self.timer.disconnect()
            pygame.quit()
 
    def openGame(self):
        self.init_pygame()
 
 
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = MyWidget2()
    result = app.exec_()
    sys.exit(result)
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
09.01.2021, 20:37
Помогаю со студенческими работами здесь

Окно открывается, но вылетает при нажатии на pushbutton.PyQT5 С чем это может быть связано? Как устранить проблему?
Пожалуйста, помогите.

Открыть окно при нажатии на баннер
Здравствуйте! Подскажите,как сделать такое, есть баннер на сайте при нажатии на нём необходимо чтобы открылась новая страница браузера с...

При нажатии на кнопку открыть pop-up окно
Здравствуйте,форумчане. Прошу помощи. Суть проблемы такова, что при нажатии заказать выскакивает форма, ее заполняешь, и чтобы сообщение...

Открыть словарь при нажатии кнопки
Помогите. Есть консольное приложение и два словаря, при нажатии цифры 1 открывался один словарь, а при нажатии цифры 2, второй словарь

Открыть папку при нажатии кнопки
Подскажите, пожалуйста, как в Delphi 7 запрограммировать кнопку (BitBtn), чтобы при ее нажатии открывалась папка (чтобы путь к папке можно...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Новые блоги и статьи
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и напряжениями. Надо найти токи в ветвях. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и решает её. Последовательность действий:. . .
Новый CodeBlocs. Версия 25.03
palva 04.01.2026
Оказывается, недавно вышла новая версия CodeBlocks за номером 25. 03. Когда-то давно я возился с только что вышедшей тогда версией 20. 03. С тех пор я давно снёс всё с компьютера и забыл. Теперь. . .
Модель микоризы: классовый агентный подход
anaschu 02.01.2026
Раньше это было два гриба и бактерия. Теперь три гриба, растение. И на уровне агентов добавится между грибами или бактериями взаимодействий. До того я пробовал подход через многомерные массивы,. . .
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru