PyGtk 中 excel 文件的 Return 路径值

Return value of path of excel file in PyGtk

我无法将从函数返回的值存储到变量中的 .connect 按钮小部件中以在我的主程序中使用它。

我在 Python 3.4 中使用 PyGtk 3+ 我需要这些程序的返回值来加载其他值并执行计算。

   button = Gtk.Button("Brwose File")
   button.connect("clicked",self.test2)  
   def test2(self,widget,mylist1,clicked):
        dialog = Gtk.FileChooserDialog("Please choose a file", None,
                                   Gtk.FileChooserAction.OPEN,
                                   (Gtk.STOCK_CANCEL, 
                                    Gtk.ResponseType.CANCEL,
                                    Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) 
       response = dialog.run()
       if response == Gtk.ResponseType.OK:
           print("Open clicked")
           a = dialog.get_filename()  

       wb = xlrd.open_workbook(a)
       sheet = wb.sheet_by_index(0)
       ncols = sheet.ncols
       print(ncols)
       nrows = sheet.nrows
       print(nrows)
       clicked.append(1)
       print(clicked)
       mylist = []
       for i in range(sheet.nrows):
           data = sheet.row_values(i)
           mylist1.append(data)
       return (mylist1)

由于事件循环的工作方式,这是不可能的。但是因为你正在使用 class 你可以只使用一个实例变量。简体:

class MyApp:
    def __init__(self):
        ...
        self.my_var = None
        button = Gtk.Button()
        button.connect("clicked", self.on_button_clicked)

    def on_button_clicked(self, widget):
        ...
        self.my_var = "something"

然后在 class 中的任何其他地方使用 self.my_var

谢谢!这些是更好的解决方案。这是我更新的代码:

def on_browse_clicked(self, widget):
    """Creates dialogue box to choose file for loading data when browse button is clicked"""

    dialog = Gtk.FileChooserDialog("Please choose a file", None,
                                   Gtk.FileChooserAction.OPEN,
                                   (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                    Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print("Open clicked")
        global file
        file = dialog.get_filename()
        dialog.destroy()
        self.browse_entry.set_text(file)
        wb = xlrd.open_workbook(file)
        sheet = wb.sheet_by_index(0)
        for i in range(1, sheet.nrows):
            data = sheet.row_values(i)
            print(data)
            self.production_data_list_store.append(data)

    else:
        dialog.destroy()