瞬态输入风

2024-10-02 22:34:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个系统,其中有一个弹出窗口,请求用户输入,然后将输入返回到代码主体进行处理。我有窗口弹出正确,使用瞬态,以确保它停留在顶部,但我无法找到一种方法,使窗口返回数据,它被调用的地方。 当前:

from tkinter import *

class loginwindow(object):
    def __init__(self, parent):
        self.parent=parent
        self.data=None #Default value, to say its not been set yet
        self.root=Toplevel(self.parent)
        self.root.transient(self.parent)
        self.username=Entry(self.root)
        self.password=Entry(self.root, show="*")
        self.ok=Button(self.root, text="Continue", command=self.checkPass); self.ok.grid(row=5, column=2, sticky="ew")
        self.cancel=Button(self.root, text="Cancel", command=self.cancelPass); self.cancel.grid(row=5, column=1, sticky="ew")


    def checkPass(self):
        self.data=(self.username.get(), self.password.get())
        self.root.quit()

    def cancelPass(self):
        self.data=False
        self.root.quit()

parent=Tk()
passWindow=loginwindow(parent)
#....? how do I get passWindow.data from the window, considering it will only be defined 
#to be something besides None once the user has clicked the continue button

我尝试过循环以等待passWindow.data的值从None更改,但是这会导致loginwindow不出现,或者脚本锁定。理想情况下,我希望保留transient,因为它可以阻止用户单击窗口,但我知道{}是窗口不出现的原因(没有它也可以正常工作)

有什么想法吗?在


Tags: theto用户fromselfnonedataget
1条回答
网友
1楼 · 发布于 2024-10-02 22:34:18

你问了两个问题,一个是关于从弹出窗口向主窗口传递一个值,另一个是关于transient不能正常工作的问题。我对第一个问题的回答如下,对于第二个问题,我真的不知道你遇到了什么问题。据我所知,^{}按照您使用它的方式工作。在


您可以使用wait_window让Tkinter主循环在继续之前等待窗口关闭。如果将弹出窗口创建放在父级主循环启动后调用的函数中,则可以使用passWindow.wait_window()在继续执行其余行之前“暂停”函数的进一步执行。窗口关闭后,可以在passWindow.data中找到所需的数据

class loginwindow(object):
    def __init__(self, parent):
        self.parent=parent
        self.data=None #Default value, to say its not been set yet
        self.root=Toplevel(self.parent)
        self.root.transient(self.parent)
        self.username=Entry(self.root); self.username.pack()
        self.password=Entry(self.root, show="*"); self.password.pack()
        self.ok=Button(self.root, text="Continue", command=self.checkPass); self.ok.pack()
        self.cancel=Button(self.root, text="Cancel", command=self.cancelPass); self.cancel.pack()

    def checkPass(self):
        self.data=(self.username.get(), self.password.get())
        self.root.destroy()

    def cancelPass(self):
        self.data=False
        self.root.destroy()


def popup():
    passWindow=loginwindow(parent)
    passWindow.parent.wait_window(passWindow.root)
    print passWindow.data

parent=Tk()
Button(parent, text='popup', command=popup).pack()
parent.mainloop()

相关问题 更多 >