python:在另一个类中使用方法类的输出 [英] python: using output from method's class inside another class

查看:37
本文介绍了python:在另一个类中使用方法类的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PyQt5(一种记忆游戏)开发我的第一个应用程序.

I am trying to develop my first app with PyQt5 (a memory game).

我创建了两个类:MainApplication,它继承自 QMainWindow,以及 GridWidget,它继承自 QWidget.我的目标是让用户使用 menuBar 的 fileMenu 指定一个包含一些图像(jpg)的文件夹.

I have created two classes: MainApplication, which inherits from QMainWindow, and GridWidget, which inherits from QWidget. My aim is to let the user specify a folder with some images (jpg) using the fileMenu of the menuBar.

因此,在 MainApplication 中,我创建了方法 showDialog 连接到 fileMenu 并输出文件名列表(所选文件夹中的图像名称),存储在列表变量中.我希望能够将其传递给 GridWidget,以便它可以创建和填充网格.

So, in the MainApplication I created the method showDialog which connects to the fileMenu and outputs a list of filenames (names of the images within the selected folder), stored in a list variable. I would like to be able to pass this to the GridWidget, so that it can creates and fill the grid.

我对 OOP 编程有点陌生,所以也许我的脚本的组织不是最好的,我愿意接受改进它的建议.我的想法是将 GridWidget 添加到 MainApplication 中,但我不知道如何将 showDialog 的输出传递给这个.任何建议将不胜感激.

I am kind of new to OOP programming, so maybe the organization of my script is not the best, and I am open to suggestions to improve it. My idea was to add GridWidget into MainApplication, but I don't know how to pass the output of showDialog to this. Any suggestion would be appreciated.

这是我目前的代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
Memory game 

My first memory game in PyQt5.

author: Umberto Minora 
last edited: September 2016
"""

import os, sys, glob
from PyQt5.QtWidgets import (QMainWindow, QWidget,
    QGridLayout, QPushButton, QApplication,
    QAction, QFileDialog)
from PyQt5.QtGui import QPixmap

class MainApplication(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.statusBar()

        openFile = QAction('Open', self)
        openFile.setStatusTip('Search image folder')
        openFile.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)

        self.form_widget = GridWidget(self)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Memory Game!')
        self.show()

    def showDialog(self):

        folder = str(QFileDialog.getExistingDirectory(self, "Select Directory", 
            '/home', QFileDialog.ShowDirsOnly))

        images = glob.glob(os.path.join(folder, '*.jpg'))

        if images:
            return images * 2

class GridWidget(QWidget):

    def __init__(self):
        super().__init__()

        grid = QGridLayout()
        self.setLayout(grid)

        names = self.showDialog() # DA SISTEMARE!!!!!!

        positions = [(i,j) for i in range(int(len(names)/2)) for j in range(int(len(names)/2))]

        for position, name in zip(positions, names):

            if name == '':
                continue
            button = QPushButton(name)
            grid.addWidget(button, *position)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MainApplication()
    sys.exit(app.exec_())

编辑

感谢 @ekhumoro 的回答,现在代码正在运行.这是我实际运行的代码(它不是完整的游戏,只是从文件夹中初始导入的图像).

Thanks to @ekhumoro's answer, now the code is working. Here is the code I am actually running (it's not the complete game, just an initial import of images from a folder).

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
Memory game 2

My first memory game in PyQt5.

author: Umberto Minora 
last edited: September 2016
"""

import os, sys, glob, math
from PyQt5.QtWidgets import (QMainWindow, QWidget,
    QGridLayout, QPushButton, QApplication,
    QAction, QFileDialog, QLabel)
from PyQt5.QtGui import QPixmap

class MainApplication(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.statusBar()

        openFile = QAction('Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Search image folder')
        openFile.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        self.fileMenu = menubar.addMenu('&File')
        self.fileMenu.addAction(openFile)

        self.gridWidget = QWidget(self)
        self.gridLayout = QGridLayout(self.gridWidget)
        self.setCentralWidget(self.gridWidget)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Memory Game!')
        self.show()

    def populateGrid(self, images):
        names = images * 2
        n_cols = math.ceil(math.sqrt(len(names)))
        n_rows = math.ceil(math.sqrt(len(names)))
        positions = [(i,j) for i in range(n_cols) for j in range(n_rows)]
        for position, name in zip(positions, names):
            if name == '':
                continue
            pixmap = QPixmap(name)
            scaled = pixmap.scaled(pixmap.width()/3, pixmap.height()/3)
            del(pixmap)
            lbl = QLabel(self)
            lbl.setPixmap(scaled)
            self.gridLayout.addWidget(lbl, *position)

    def showDialog(self):
        folder = str(QFileDialog.getExistingDirectory(self, "Select Directory",
            '.', QFileDialog.ShowDirsOnly))

        images = glob.glob(os.path.join(folder, '*.jpg'))

        if images:
            self.populateGrid(images)


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MainApplication()
    sys.exit(app.exec_())

推荐答案

我认为如果将所有内容都放在一个类中会更简单.您应该使每个子小部件成为类的一个属性,以便以后可以在类的方法中使用 self 访问它们.所有程序逻辑都将包含在方法中 - 所以这只是调用方法以响应信号和事件的问题.

I think it will be simpler if you keep everything in one class. You should make each child widget an attribute of the class, so you can access them later using self within the methods of the class. All the program logic will go in the methods - so it's just a matter of calling methods in response to signals and events.

类应该如下所示:

class MainApplication(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.statusBar()

        openFile = QAction('Open', self)
        openFile.setStatusTip('Search image folder')
        openFile.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        self.fileMenu = menubar.addMenu('&File')
        self.fileMenu.addAction(openFile)

        self.gridWidget = QWidget(self)
        self.gridLayout = QGridLayout(self.gridWidget)
        self.setCentralWidget(self.gridWidget)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Memory Game!')
        self.show()

    def populateGrid(self, images):
        names = images * 2
        positions = [(i,j) for i in range(int(len(names)/2)) for j in range(int(len(names)/2))]
        for position, name in zip(positions, names):
            if name == '':
                continue
            button = QPushButton(name)
            self.gridLayout.addWidget(button, *position)

    def showDialog(self):
        folder = str(QFileDialog.getExistingDirectory(self, "Select Directory",
            '/home', QFileDialog.ShowDirsOnly))

        images = glob.glob(os.path.join(folder, '*.jpg'))

        if images:
            self.populateGrid(images)

这篇关于python:在另一个类中使用方法类的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆