简体   繁体   English

按下键时如何打开tkinter窗口

[英]How to open a tkinter window when a key is pressed

I have this code: 我有以下代码:

from tkinter import *
import keyboard
#console
if keyboard.is_pressed('c'):
    console=Tk()
    console.geometry("500x425")
    console.title("Devoloper Console")
    console.resizable(True,True)
    console.configure(bg='gray95')

Basically, I'm trying to use the keyboard module to detect when I press C on my keyboard, and then open a Tkinter window when I press C . 基本上,我试图使用键盘模块检测何时按下键盘上的C ,然后在按下C时打开Tkinter窗口。

The code above doesn't work (obviously) and I don't know why. 上面的代码不起作用(显然),我也不知道为什么。 However, I do know that the problem is that it isn't detecting the keypress and not a problem with the window. 但是,我确实知道问题在于它没有检测到按键,也不是窗口有问题。

You need a continuing loop to check when c is pressed. 您需要一个连续的循环来检查何时按下c

from tkinter import *
import keyboard

x = True

while x:
    if keyboard.is_pressed('c'):
        x = False
        console=Tk()
        console.geometry("500x425")
        console.title("Devoloper Console")
        console.resizable(True,True)
        console.configure(bg='gray95')
        console.mainloop()
import tkinter as tk
import keyboard

while (not keyboard.is_pressed("c")):
       pass

root = tk.Tk()
root.bind("<c>", lambda e: tk.Toplevel())
root.mainloop()

Does this do what you wanted? 这是您想要的吗?

Module keyboard has a function called wait . 模块keyboard具有称为wait的功能。 It waits for a key to be pressed. 它等待按键被按下。 You have to use that. 您必须使用它。 Also use mainloop for the tkinter window to make it run corectly. 还可以对mainloop窗口使用mainloop使其核心运行。

import tkinter as tk
import keyboard

keyboard.wait("c")   #< It'll wait for c to be pressed

console = tk.Tk()
console.geometry("500x425")
console.title("Devoloper Console")
console.resizable(True,True)
console.configure(bg='gray95')
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM