【问题标题】:use a variable defined in a function outside the function在函数外使用函数中定义的变量
【发布时间】:2021-09-30 09:16:41
【问题描述】:

我这里有这个功能。

def choose_file():
    file = askopenfile(mode ='r', filetypes =[('xodr Files', '*.xodr')])
    if file:
        res = "selected:", file
    else:
        res = "file not selected"
    return(res)

我有这个按钮来打开对话框并选择一个文件

e3=Button (scalF, text='Wählen Sie ein Dokument',font=('Bahnschrift SemiLight',12),command=choose_file, bg='blue')
e3.pack(side='top')

选择一个文件并关闭对话框后,我想在下面的标签中显示choose_file() 中定义的变量 res 的值

chosenFile = Label(scalF,text="I want to write here",font=('Bahnschrift SemiLight', 10))
chosenFile.pack(side='top')

你能解释一下如何从全局范围内读取变量res吗?

【问题讨论】:

    标签: python function tkinter


    【解决方案1】:

    您可以使用tk.StringVar to hold the strings variables

    file_result = tk.StringVar() 定义选择文件(): file = askopenfile(mode ='r', filetypes =[('xodr Files', '*.xodr')]) 如果文件: res = "选择:{0}".format(file.name) 别的: res = "未选择文件" file_result.set(res)

    然后这个变量(file_result)可以传递给Labels textvariable argument(将使用其值代替文本)。

    selectedFile = Label(scalF, font=('Bahnschrift SemiLight', 10), textvariable=file_result)

    【讨论】:

    • 它有效。谢谢!! @Abdul Niyas P M 只有一个问题:我的函数 choose_file() 在 root = Tk() 内,所以我将 file_result = tk.StringVar() 移动到 root = Tk() 下。这是最好的做法还是我也应该将函数移到 root = Tk() 下?
    【解决方案2】:

    我可以推荐的方法之一是: 在函数的第一行添加global res

    【讨论】:

      【解决方案3】:

      您可以通过使用global 关键字声明它来在全局范围内使用该变量。

      def choose_file():
          global res
          file = askopenfile(mode ='r', filetypes =[('xodr Files', '*.xodr')])
          if file:
              res = "selected:", file
          else:
              res = "file not selected"
          return(res)
      

      如果你想了解更多,可以在 python 中了解namespaces

      【讨论】:

        【解决方案4】:

        你可以使用一个类:

        class File():
            def __init__(self):
                self.res = None
        
                e3=Button (scalF, text='Wählen Sie ein Dokument', font=('Bahnschrift SemiLight',12), command=self.choose_file, bg='blue')
                e3.pack(side='top')
        
            def choose_file(self):
                # Your implementation but updating self.res, without return
        
            def get_res(self):
                return self.res
        

        【讨论】:

          猜你喜欢
          • 2019-01-07
          • 2023-03-24
          • 1970-01-01
          • 1970-01-01
          • 2013-05-02
          • 2021-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多