繁体   English   中英

函数未使用全局变量

[英]global variable not being used by functions

我定义了这些全局变量:

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")

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

正如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被直接修改,并保持其新值。

假设我相信您正在使用tkinter,则无需进行任何全局分配。

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

参见下文,def callback(self)是您的功能1

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()

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

value1 = "Hello"
value = "World"
def function1():
    global value1
    global value
    print(value1, value1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM