【问题标题】:Get variable value created inside a function获取在函数内部创建的变量值
【发布时间】:2021-03-25 00:39:19
【问题描述】:

我想从一个函数中获取一个变量,以便在另一个函数中使用这个变量。 简单例子:

from tkinter import *

def test():

    intro = "I am "
    name = "Phil"
    text = intro + name


def printresult():
    print(text)


root = Tk()
root.title("Test")

testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)

testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)

mainloop()

如果我按testbutton,然后按printbutton,则会收到错误“名称'文本'未定义”。

那么我怎样才能从def test() 中获取text 变量以在def printresult() 中使用它?

【问题讨论】:

    标签: python function tkinter


    【解决方案1】:

    您需要将值保存在众所周知的地方:

    from tkinter import *
    
    def test():
        intro = "I am "
        name = "Phil"
        text = intro + name
        test.text = text     # save the variable on the function itself
    
    
    def printresult():
        print(test.text)
    
    
    root = Tk()
    root.title("Test")
    
    testbutton = Button(root, text="Test", command = test)
    printbutton = Button(root, text="print Test", command = printresult)
    
    testbutton.grid(row = 1, column = 0)
    printbutton.grid(row = 1, column = 1)
    
    mainloop()
    

    【讨论】:

      【解决方案2】:

      由于您使用的是 tkinter,我会使用 StringVar 来存储结果。使用字符串 var 可以让其他 tkinter 小部件轻松使用该值。

      from tkinter import *
      
      def test():
      
          intro = "I am "
          name = "Phil"
          text.set(intro + name)
      
      
      def printresult():
          print(text.get())
      
      
      root = Tk()
      root.title("Test")
      
      text = StringVar()
      
      testbutton = Button(root, text="Test", command = test)
      printbutton = Button(root, text="print Test", command = printresult)
      
      testbutton.grid(row = 1, column = 0)
      printbutton.grid(row = 1, column = 1)
      
      mainloop()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-12
        • 2018-09-02
        • 2011-03-31
        • 2018-02-13
        • 2013-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多