Python跨文件读取全局变量:PyQt5 MAC修改程序报错解决
解决PyQt5跨窗口变量传递导致的NameError问题
问题描述
你在Linux下基于PyQt5开发的MAC地址修改工具中,主窗口文件mac_2.py定义的全局变量connection无法被子窗口文件mac_specific.py读取,点击子窗口的确定按钮时触发NameError: name 'connection' is not defined错误,无法完成MAC地址修改操作。
解决方案
全局变量跨模块访问本身不符合面向对象设计规范,且容易引发作用域问题。我们可以通过主窗口实例传递状态的方式解决这个问题,具体步骤如下:
1. 修改主窗口mac_2.py,将全局变量改为实例属性
在select方法中,去掉global connection声明,把connection改为当前窗口实例的属性:
def select(self): if self.radioButton.isChecked(): self.wired = config.get('ethernet', 'wired') self.label.setText(str(self.wired)) self.connection = self.wired # 改为实例属性 self.mac_address = config.get('ethernet', 'wired_mac_address') self.label_2.setText(str(self.mac_address)) if self.radioButton_2.isChecked(): self.wireless = config.get('wifi', 'wireless') self.label.setText(str(self.wireless)) self.connection = self.wireless # 改为实例属性 self.mac_address = config.get('wifi', 'wireless_mac_address') self.label_2.setText(str(self.mac_address))
2. 修改子窗口mac_specific.py,通过主窗口实例获取状态
首先删除文件开头直接读取config的代码(避免未导入config导致的错误):
# 删掉以下两行 # wired = config.get('ethernet', 'wired') # wireless = config.get('wifi', 'wireless')
然后修改clicked_button方法,通过self.master(主窗口实例)访问connection和接口名称:
def clicked_button(self): print("submit") text = self.lineEdit.text() self.master.label_2.setText(text) # 通过主窗口实例获取当前选中的网络接口 current_connection = self.master.connection subprocess.run(['pkexec', 'ifconfig', current_connection, 'down']) subprocess.run(['pkexec', 'ip', 'link', 'set', 'dev', current_connection, 'address', text]) subprocess.run(['pkexec', 'ifconfig', current_connection, 'up']) self.window.close()
原理说明
子窗口在setupUi方法中已经接收了主窗口实例(master参数),通过访问主窗口的实例属性connection,可以安全获取当前选中的网络接口,避免了全局变量的作用域问题,同时更符合PyQt的面向对象设计逻辑。
内容的提问来源于stack exchange,提问作者user21379959
相关产品推荐
相关产品推荐

