微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Tk 窗口不存储变量?

如何解决Tk 窗口不存储变量?

好的,我如何让用户将某些内容输入到 tk 窗口中以将其输出到变量中? 好的,所以我正在为我的程序制作一个选项菜单,我想在 tk 窗口之外使用“answer”变量。但是,一旦窗口关闭,该变量将变为未定义。如何在 tk 窗口关闭后保存它以便我可以在 pygame 窗口中继续使用它?

import pygame,time,math,sys
import tkinter as tk
from pygame.locals import *
from tkinter import *

def options():
    root = Tk()
    root.geometry("300x100")
    root.title('PyCott Options')

    

    def ctime():
        master = Tk()
        e = Entry(master)
        e.pack()
        

        e.focus_set()

        def callback():
            answer = (e.get())
            master.destroy()
            root.destroy()

        b = Button(master,text = "OK",width = 10,command = callback)
        b.pack()

        master.mainloop()
        

    b = Button(text = "Change time",command = ctime)
    b.pack()

    answer = e
    root.mainloop()

#Here,I open the option menu

options()

#However,here,even thought I defined it in the tk window,it becomes undefined outside of it

我知道这不是很清楚,但我没能更好地解释它。另外,我对 python 比较陌生,所以其中一些代码是......假设我借用了它。

解决方法

我猜你收到了

NameError: name 'e' is not defined

这是因为 e 是在 ctime 中定义的,它在 e 第一次被评估时还没有被调用。

,
  • 最好不要对根窗口以外的窗口使用 Tk()。使用Toplevel()

  • 需要在nonlocal answer里面加上callback()来表示answer不是callback()里面的局部变量

  • 使弹出输入窗口像一个模态对话框

  • answer = e改为answer = <whatever initial value you want>

  • options()

    末尾返回答案
  • 在调用options()时保存返回值,然后你可以在其他地方使用它

以下是修改后的代码:

from tkinter import *

def options():
    root = Tk()
    root.geometry("300x100")
    root.title('PyCott Options')

    def ctime():
        master = Toplevel()  # use Toplevel() instead of Tk()

        e = Entry(master)
        e.pack()
        e.focus_set()

        def callback():
            nonlocal answer   # indicate that answer is not local variable
            answer = e.get()
            master.destroy()
            root.destroy()

        b = Button(master,text = "OK",width = 10,command = callback)
        b.pack()

        # make the popup as a modal dialog
        master.grab_set()


    b = Button(text = "Change time",command = ctime)
    b.pack()

    answer = None   # initial value for answer,change to whatever you want
    root.mainloop()
    return answer

# store the return answer from options()
answer = options()
print(answer)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。