在python 3.6中覆盖alt-f4关闭tkinter窗口并将其替换为其他内容 [英] override alt-f4 closing tkinter window in python 3.6 and replace it with something else
问题描述
我花了很长时间阅读过去的帖子,但没有找到我需要的内容.
I spent a long time reading through past posts and didn't find quite what I need.
我正在使用 tkinter 制作 kiosk 类型的窗口.我设置为全屏打开.我想覆盖标准的 alt-f4 命令来关闭它.我不希望它完全无法关闭.我想改用自己的键盘快捷键(alt-ctrl-g-3 或类似的东西).
I'm making a kiosk-type window using tkinter. I set it to open fullscreen. I want to override the standard alt-f4 command to close it. I don't want it completely uncloseable though. I'd like to instead make up my own keyboard shortcut (alt-ctrl-g-3 or something like that).
我尝试了一些覆盖 alt-f4 的建议,但无法使它们起作用.在我的 init 函数中,我包含了:
I tried some of the suggestions for overriding alt-f4 and couldn't get them to work. In my init function I included:
self.bind('<Alt-Key-F4>', self.ignorekey())
.
.
.
def self.ignorekey(self)
pass
推荐答案
就我所知,有一种方法可以挂接 Alt+F4 或按 X 或任何其他方式:>
There is a way to hook the Alt+F4 or pressing the X or any other way as far as I know:
root.protocol("WM_DELETE_WINDOW", do_exit)
其中 do_exit()
是回调函数,root
是您的主窗口.
where do_exit()
is the callback function and root
is your main window.
此绑定不传递事件对象.据我所知,这应该适用于任何平台.
This binding does not pass an event object. As far as I can see this should work for any platform.
这是一个例子:
from tkinter import *
root = Tk()
pressed_f4 = False # Is Alt-F4 pressed?
def do_exit():
global pressed_f4
print('Trying to close application')
if pressed_f4: # Deny if Alt-F4 is pressed
print('Denied!')
pressed_f4 = False # Reset variable
else:
close() # Exit application
def alt_f4(event): # Alt-F4 is pressed
global pressed_f4
print('Alt-F4 pressed')
pressed_f4 = True
def close(*event): # Exit application
root.destroy()
root.bind('<Alt-F4>', alt_f4)
root.bind('<Escape>', close)
root.protocol("WM_DELETE_WINDOW",do_exit)
root.mainloop()
我不确定来自 root.bind('<Alt-F4>', alt_f4)
的回调总是会在来自 root.protocol("WM_DELETE_WINDOW",do_exit)
.你可能需要做更多的研究来确定这一点.
I'm not sure that the callback from root.bind('<Alt-F4>', alt_f4)
always will run before the callback from root.protocol("WM_DELETE_WINDOW",do_exit)
. You may have to do more research to establish that.
这篇关于在python 3.6中覆盖alt-f4关闭tkinter窗口并将其替换为其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!