python - 如何在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 文件制作的,但我认为问题不取决于它
解决方案
如果您真的想使用全局变量,那您就不能这样做
filename = "test.jpg"
image = Image.Open(filename)
...
在顶部?
推荐阅读
- react-native - ReactNative:导航选项不起作用
- swift - NSTableColumn 使用 Core Data 字典排序
- android - 有没有办法在绑定适配器函数中使用存储库或视图模型对象?
- python - pandas 按所有值小于特定数字的列值分组,并将组号分配为新列
- css - 用动画向左展开 div 会导致“抖动”
- python - 当 IP 用作 ARP 数据包中的范围时,Scapy 不起作用
- java - java - 当Json数据在没有db的情况下在java play框架中进入postman时如何增加id值?任何人都可以帮助如何生成 id 值
- r - 合并 purrr::map 中的函数
- javascript - Visual Studio 和 Visual Studio 代码,“转到定义”不适用于带有 index.d.ts 文件的第三方 javascript 模块
- c++ - 我应该安装 .cmake 文件来共享/cmake 还是 lib/cmake?