Python Tkinter-无法从另一个方法设置的全局变量中获取值
我试图将保存的全局变量的值插入到文本框中,但由于某些未知原因,即使保存的是全局变量,它也只能显示在分配值(字符串)的方法中Python Tkinter-无法从另一个方法设置的全局变量中获取值,python,tkinter,text,Python,Tkinter,Text,我试图将保存的全局变量的值插入到文本框中,但由于某些未知原因,即使保存的是全局变量,它也只能显示在分配值(字符串)的方法中 note=文本(根) 注:位置(relx=0.1,rely=0.65,relwidth=0.85,relheight=0.3) 全局保存 def保存注释(注释): 尝试: 保存=注意。获取(1.0,结束)#没问题! messagebox.showinfo(“成功!”,已保存) 除: messagebox.showinfo(“错误”,“无法保存”) def get_注释(注释
note=文本(根)
注:位置(relx=0.1,rely=0.65,relwidth=0.85,relheight=0.3)
全局保存
def保存注释(注释):
尝试:
保存=注意。获取(1.0,结束)#没问题!
messagebox.showinfo(“成功!”,已保存)
除:
messagebox.showinfo(“错误”,“无法保存”)
def get_注释(注释):
尝试:
注意。插入(索引=结束,字符=保存)#问题?!
除:
messagebox.showinfo(“错误”,“无法获取注释”)
下面是使用命令save_note和get_note的按钮
button16=Button(root,text=“SAVE”,bg='white',fg='black',command=lambda:SAVE_note(note))
按钮16.放置(relx=0.05,rely=0.65,relwidth=0.04,relheight=0.15)
button17=按钮(root,text=“Get”,bg='white',fg='black',command=lambda:Get_note(note))
按钮17.放置(relx=0.05,rely=0.80,relwidth=0.04,relheight=0.15)
在这行代码中,我无法在文本框中插入saved的值
note.insert(index=END,chars=saved)#问题?!
在应用某些OOP失败后,我尝试了save.get()。我已通过检查保存的var值
messagebox.showinfo(“成功!”,已保存)
没有问题-保存的内容包含我键入的所有内容。
你能为我面临的这个问题提出一个解决方案吗?
谢谢大家! 这是因为方法
save\u note
创建了一个新的局部变量,而不是更新局部变量saved
您的代码应该是:
def save_note(note):
global saved
try:
saved = note.get(1.0, END) # No problem!
messagebox.showinfo("Success!", saved)
except:
messagebox.showinfo("Error", "Can't save")
def get_note(note):
global saved
try:
note.insert(index=END, chars=saved) # Problem?!
except:
messagebox.showinfo("Error", "Can't get notes")
global关键字用于在本地导入全局变量,或者如果不存在,则创建全局变量。非常感谢这回答了我的问题!我没想到全局变量会是这样:0