首页 > 解决方案 > 如何在python中定义空变量或将值从函数传递给全局变量?

问题描述

我正在制作某种基本的图像过滤器应用程序。我有一个打开和初始化图像的函数,但变量只保留在函数中,我无法从另一个函数中获取它们,所以我需要定义全局变量?

我尝试全局定义变量并使用示例图像对其进行初始化,然后在函数中我将新数据分配给该变量(或不?)但似乎打开文件的函数不会重写全局变量,因此我的过滤器函数适用于我的示例图像,而不是我打开的目标图像。

image = Image.open("test.jpg")
draw = ImageDraw.Draw(image)  
width = image.size[0]  
height = image.size[1]      
pix = image.load()

class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.load_file.triggered.connect(self.load_image) #Can I here call load_image with arguments? How?
        self.grayscale.triggered.connect(self.Grayscale)
    def browse_file(self):
        file_name = QtWidgets.QFileDialog.getOpenFileName(self, 'Pick a picture',"","JPEG (*.jpg;*.jpeg);;PNG (*.png);;All Files (*)")[0]
        if file_name:
            print (file_name)
            return file_name
        else:
            print("File couldn't be open")
            return 0
    def load_image(self): 
        file_name = self.browse_file()
        pixmap = QPixmap(file_name)
        self.pic_box.setPixmap(pixmap)
        self.pic_box.resize(pixmap.width(), pixmap.height())
        print(pixmap.width(), pixmap.height())
        self.resize(pixmap.width(), pixmap.height())
        image = Image.open(file_name) #Here I'm trying assign new image and it's properties to variables I defined on the first lines
        draw = ImageDraw.Draw(image) 
        width = image.size[0]  
        height = image.size[1]      
        pix = image.load()
        self.show()
    def Grayscale(self): #Function works with test.jpg, not with file I'm trying to load
        for i in range(width):
            for j in range(height):
                a = pix[i, j][0]
                b = pix[i, j][1]
                c = pix[i, j][2]
                S = (a + b + c) // 3
                draw.point((i, j), (S, S, S))
        image.save("Grayscale.jpg", "JPEG")

我的目标是以某种方式将带有文件名的字符串传递给全局变量,以便每个函数都可以访问它。还有其他design.py文件,我是用 QtDesigner 的 .ui 文件制作的,但我认为问题不取决于它

标签: pythonpyqtpyqt5

解决方案


如果您真的想使用全局变量,那您就不能这样做

filename = "test.jpg"
image = Image.Open(filename)
...

在顶部?


推荐阅读