我想知道是否可以在方法中声明一个全局变量,以便可以在另一个UI方法中调用和使用它。我在下面编写的代码应该采用用户选择的阈值文件,然后在单击运行按钮时将其打印出来。
class Handler:
def on_filechooserbutton1_file_set(self, widget):
self.Thresholds = widget.get_filename()
with self.Thresholds as a:
global Thresholds
Thresholds = pd.read_table(a, sep=',')
def on_RUN_clicked(self, widget):
print Thresholds
def onDeleteWindow(self, *args):
Gtk.main_quit(*args)
builder = Gtk.Builder()
builder.add_from_file("DataAPP.glade")
builder.connect_signals(Handler())
window = builder.get_object("MainWindow")
window.show_all()
Gtk.main()
print Thresholds
阈值变量包含一个数据帧,并且之前已经定义过,但每当我尝试在其方法之外调用阈值变量时,我会收到错误说明:
NameError: global name 'Thresholds' is not defined
关于如何正确地做这件事的任何建议?
答案 0 :(得分:1)
您应首先创建全局变量:
Thresholds = None
class Handler:
...
答案 1 :(得分:0)
事实证明我打开文件的语法是错误的。要在单击按钮和主脚本中打印阈值文件,以下代码将起作用:
class Handler:
def on_filechooserbutton1_file_set(self, widget):
self.Thresholds = widget.get_filename()
with open (self.Thresholds) as a:
global Thresholds
Thresholds = pd.read_table(a, sep=',')
def on_RUN_clicked(self, widget):
print Thresholds
def onDeleteWindow(self, *args):
Gtk.main_quit(*args)
builder = Gtk.Builder()
builder.add_from_file("DataAPP.glade")
builder.connect_signals(Handler())
window = builder.get_object("MainWindow")
window.show_all()
Gtk.main()
print Thresholds