grab_set() 函数在 tkinter 中不起作用 [英] grab_set() function not working in tkinter
问题描述
我之前问过一个关于相同的问题,这里是一个链接:眨眼"如果单击父窗口,则提示窗口 Tkinter
I have asked a question previously about the same, here is a link to that: "Blink" Prompt window if parent window is clicked Tkinter
但它被标记为重复.请帮助我编写代码,因为即使经过反复尝试,我也无法在我的代码中实现grab_set().有人建议我提出一个新问题,所以在这里.
But it was marked as duplicate. Please help me with my code as I am not able to implement grab_set() in my code even after repeated tries. I was advised to open a new question, so here it is.
我的代码:
import tkinter
from tkinter import *
def mainwindow():
root = Tk()
root.geometry("100x100")
b1 = Button(root, text="Exit", command=prompt)
b1.place(x=50, y=40)
mainloop()
def prompt():
pr = Tk()
pr.geometry("175x100")
pr.grab_set()
lable = Label(pr, text="Do you want to exit?").grid(row=0, column=0, padx=20, pady=15)
b1 = Button(pr, text="Yes", command=exit).grid(row=1, column=0, padx=75)
mainloop()
mainwindow()
即使将 grab_set()
放在 pr
窗口后,我也可以访问 root
窗口.请告诉将这个函数放入我的代码中的正确方法.
Even after putting grab_set()
on the pr
window , I can access the root
window. Please tell the correct way to put this function inside my code.
推荐答案
您的代码有一些问题,如前一个答案中指出的(第二个使用 Toplevel
而不是 Tk
window 并仅使用 mainloop
一次)和其他一些您应该避免的更多内容,例如两次导入 tkinter,在局部变量的函数内创建根窗口,或执行 b1 = Button(..).grid(...)
,当 grid()
方法没有返回任何东西时,所以 b1 = None
.除此之外,对于退出应用程序提示,我认为您会更喜欢使用 grab_set_global()
,但正如我之前告诉您的,您必须小心使用抓取,因为 tkinter 只能抓取具有已映射到屏幕上,因此您需要先使用 wait_visibility()
.这是您的代码的改进:
Your code has some problems like pointed in previous answer (use Toplevel
instead of Tk
for the second window and use mainloop
only once) and a few other mores that you should avoid, like importing tkinter twice, creating the root window inside a function in a local variable, or doing b1 = Button(..).grid(...)
, when the grid()
method doesn't return anything so b1 = None
. Beside that, for an exit application prompt, I think you will prefer to use grab_set_global()
, but as I told you before, you have to be careful with grab since tkinter can only grab a window that has been mapped on the screen, thus you need to use wait_visibility()
before. Here is an improvement of your code:
from tkinter import *
def mainwindow():
root.geometry("100x100")
b1 = Button(root, text="Exit", command=prompt)
b1.place(x=50, y=40)
def prompt():
pr = Toplevel()
pr.geometry("175x100")
pr.wait_visibility()
pr.grab_set_global()
label = Label(pr, text="Do you want to exit?").grid(row=0, column=0, padx=20, pady=15)
Button(pr, text="Yes", command=exit).grid(row=1, column=0, padx=75)
root = Tk()
mainwindow()
root.mainloop()
这篇关于grab_set() 函数在 tkinter 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!