【问题标题】:Using a variable from a function outside the function使用函数外函数中的变量
【发布时间】:2013-05-02 03:31:01
【问题描述】:

我正在编写这个可以打开文本文档的基本 Tk 程序,但我似乎可以让它工作

这是我的代码:

from Tkinter import *
from tkFileDialog import askopenfilename
def openfile():
   filename = askopenfilename(parent=root)
   f = open(filename)
   x = f.read()
   return x


root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=openfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)


text = Text(root)
text.insert(INSERT,(x))

text.pack()

root.config(menu=menubar)
root.mainloop()

我试图在我的 tk 窗口中输入x,但它说它没有定义,即使我返回了 x

为什么这行不通,我确定它很简单,但我想不通!

【问题讨论】:

    标签: python function text tkinter return


    【解决方案1】:

    所以你这里有两个相关的问题。

    1. 您正在尝试使用 x,即使您尚未定义它
    2. openfile 返回任何内容在这种情况下都不起作用,因为您不能将其设置为另一个变量(如 x

    您可能想要做的是读取文件并将其插入到Text 小部件中,所有这些都在同一个函数调用中。试试这样的,

    from Tkinter import *
    from tkFileDialog import askopenfilename
    
    def openfile():
        filename = askopenfilename(parent=root)
        f = open(filename)
        x = f.read()
        text.insert(INSERT,(x,))
    
    root = Tk()
    menubar = Menu(root)
    filemenu = Menu(menubar, tearoff=0)
    filemenu.add_command(label="Open", command=openfile)
    filemenu.add_separator()
    filemenu.add_command(label="Exit", command=root.quit)
    menubar.add_cascade(label="File", menu=filemenu)
    
    text = Text(root)
    text.pack()
    
    root.config(menu=menubar)
    root.mainloop()
    

    【讨论】:

      【解决方案2】:

      当你从一个函数返回一个值时,你需要把它赋值给一个变量,像这样(伪代码):

      myVariable = openfile()
      

      然后你可以在你的参数中使用这个变量:

      text.insert(INSERT, (myVariable))
      

      变量 x 是在函数中定义的,所以它超出了范围。

      【讨论】:

      • 当我这样做时,当我运行 GUI 时它只是打开文件对话框而不是打开 GUI 然后等待用户单击打开
      • @ChristianCareaga 在这台计算机上没有 python,否则我会为你检查代码。对不起。
      猜你喜欢
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-21
      • 2013-08-09
      • 2022-10-04
      相关资源
      最近更新 更多