【问题标题】:Tkinter - Unable to get value from a global var set by another methodTkinter - 无法从另一种方法设置的全局变量中获取值
【发布时间】:2021-05-27 15:20:22
【问题描述】:

我试图将保存的全局变量的值插入我的文本框中,但由于某种未知原因,即使保存的是全局变量,它也只能显示在分配值(字符串)的方法中。

note = Text(root)
note.place(relx=0.1,rely=0.65, relwidth=0.85, relheight=0.3)

global saved
def save_note(note):
    try:
        saved = note.get(1.0, END) # No problem!
        messagebox.showinfo("Success!", saved)
    except:
        messagebox.showinfo("Error", "Can't save")

def get_note(note):
    try:
        note.insert(index=END, chars=saved) # Problem?!
    except:
        messagebox.showinfo("Error", "Can't get notes")

以下是使用命令 save_note 和 get_note 的按钮

button16 = Button(root, text="SAVE", bg='white', fg='black', command=lambda:save_note(note))
button16.place(relx=0.05, rely=0.65, relwidth=0.04, relheight=0.15)

button17 = Button(root, text="Get", bg='white', fg='black', command=lambda:get_note(note))
button17.place(relx=0.05, rely=0.80, relwidth=0.04, relheight=0.15)

在这行代码中,我无法在文本框中插入保存的值

note.insert(index=END, chars=saved) # Problem?!

在未能应用某些 OOP 后,我尝试了 saved.get()。我已经通过

检查了保存变量的值
messagebox.showinfo("Success!", saved)

没有问题 - 保存的包含我输入的所有内容。

您能否就我面临的这个问题提出解决方案? 谢谢!

【问题讨论】:

    标签: python tkinter text


    【解决方案1】:

    这是因为save_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
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2015-12-09
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    相关资源
    最近更新 更多