全局变量未被函数使用

问题描述 投票:0回答:3

我定义了这些全局变量:

value1 = ""
value = ""

这两个变量都用于两个不同的函数:

def function1():
  ...
  value1 = widget.get(selection1[0])

def function2():
  ...
  value = widget.get(selection0[0])

但是,当我尝试在第三个函数中使用这些变量时:

def function1():
  if value1 != "":
    if value != "":
      print(value1 + " | " + value
  else:
      print("Bar")

我只得到一个|而不是变量,而应该填充。

python tkinter
3个回答
3
投票

正如jasonharper的评论所提到的,你需要使用global关键字来引用全局变量,否则你会创建一个新的范围变量。

没有全球:

x = 3

def setToFour():
    x = 4
    print(x)

print(x)
setToFour()
print(x)

输出:

>> 3
>> 4
>> 3

该函数制作自己的x,将其设置为4,并打印出来。全球x保持不变。

全球:

x = 3

def setToFour():
    global x
    x = 4
    print(x)

print(x)
setToFour()
print(x)

输出:

>> 3
>> 4
>> 4

该函数被告知使用全局x而不是制作自己的x,将其设置为4,然后打印它。全球x被直接修改,并保持其新的价值。


1
投票

假设我相信你正在使用tkinter,你不需要任何全局任务。

您需要面向对象的方法和正确的工具,例如StringVar()或IntVar()取决于变量的性质。

看下面,def回调(自我),是你的function1

import tkinter as tk

class App(tk.Frame):

    def __init__(self,):

        super().__init__()

        self.master.title("Hello World")

        self.value = tk.StringVar()
        self.value1 = tk.StringVar()

        self.init_ui()

    def init_ui(self):

        self.pack(fill=tk.BOTH, expand=1,)

        f = tk.Frame()

        tk.Label(f, text = "Value").pack()
        tk.Entry(f, bg='white', textvariable=self.value).pack()

        tk.Label(f, text = "Value1").pack()
        tk.Entry(f, bg='white', textvariable=self.value1).pack()

        w = tk.Frame()

        tk.Button(w, text="Print", command=self.callback).pack()
        tk.Button(w, text="Reset", command=self.on_reset).pack()
        tk.Button(w, text="Close", command=self.on_close).pack()

        f.pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
        w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=0)


    def callback(self):

        if self.value1.get():
            if self.value.get():
                print(self.value1.get() + " | " + self.value.get())
        else:
            print("Foo")

    def on_reset(self):
        self.value1.set('')
        self.value.set('')

    def on_close(self):
        self.master.destroy()

if __name__ == '__main__':
app = App()
app.mainloop()

0
投票

使用赋值运算符,变量在python函数中本地创建。需要明确声明变量全局。例如。

value1 = "Hello"
value = "World"
def function1():
    global value1
    global value
    print(value1, value1)
© www.soinside.com 2019 - 2024. All rights reserved.