(我的代码正在生成此错误 to_text.insert(结束,'点击并说...') NameError:未定义名称“to_text” 如果我在主窗口和之后创建框架,这个编程运行正常 然后#calling只有temp_fun()。但我的代码需要访问框架小部件)
from tkinter import *
def frame1():
f1=Frame(winchat).pack()
to_text=Text(f1).pack()
def temp_fun():
to_text.insert(END,'Click and Say...')
winchat=Tk()
frame1()
temp_fun()
答案 0 :(得分:1)
您需要保留to_text的引用,以便可以在其他函数上访问它,因为您可以尝试将其用作全局变量。
from tkinter import *
to_text = None #<--- declaring it first.
def frame1():
f1=Frame(winchat)
f1.pack()
to_text=Text(f1)
to_text.pack()
def temp_fun():
to_text.insert(END,'Click and Say...')
winchat=Tk()
frame1()
temp_fun()
一旦你这样声明,就可以在任何函数中引用它。
答案 1 :(得分:1)
最好在全局名称空间中创建框架和文本框。
这样您就可以从其他功能编辑它们。请注意,如果您想稍后编辑窗口小部件,则需要在单独的行中使用pack()
,否则当您尝试编辑窗口小部件时,它将返回None
。
看一下下面的例子。
from tkinter import *
def temp_fun():
global to_text # tell the function you want to edit this item in global
to_text.insert(END,'Click and Say...')
winchat=Tk()
f1=Frame(winchat)
f1.pack()
to_text=Text(f1)
to_text.pack()
temp_fun()
winchat.mainloop()
在这种情况下你不需要在函数中添加全局因为python最终会检查全局,因为函数中没有定义to_text
,但是为了准确,我在这里添加了全局。