在Python中图形窗口中显示信息

0 投票
1 回答
925 浏览
提问于 2025-04-17 20:46

我正在写一个程序,目标是当用户按下笔记本电脑的某个键时,显示相应的信息。

下面是这个程序:

# Python program
# to display the fruit information
# User will press a key, and based on the key pressed, the fruit information will be diplayed
# If user presses a wrong key, then, a message will be displayed asking him to press the right key
# On pressing 'Q', the program exits
# The user will not have any idea that what are the correct keys

from msvcrt import getch

def main():

    print (40 * '-')
    print ("   F R U I T - I N F O R M A T I O N")
    print (40 * '-')


    while True:
        ## Get input ###

        choice = getch()

        if choice == 'W':
                print (80 * '-')
                print ("You have chosen Orange...")
                print ("Here's the nutritional fact of the Orange:")
                print ("'One medium orange contains 1.23 grams of protein, 62 calories and 3.1 grams of dietary fiber.'")
                print (80 * '-')

        elif choice == 'A':
                print (80 * '-')
                print ("You have chosen Banana...")
                print ("Here's the nutritional fact of the Banana:")
                print ( "'One medium banana contains 1.29 grams of protein, 105 calories and 3.1 grams of dietary fiber")
                print (80 * '-')

        elif choice == 'S':
                print (80 * '-')
                print ("You have chosen Apple...")
                print ("Here's the nutritional fact of the Apple:")
                print ("'One medium apple with skin contains 0.47 grams of protein, 95 calories, and 4.4 grams of dietary fiber.'")
                print (80 * '-')


        elif choice == 'Q':
                print "See you CHUMP!"
                break;

        else:
                print "Hey mofo, choose the fruit which we have!"
                continue;
main()

当用户按下 'W' 键时,会显示“橙子”的信息。如果用户按错了键,程序会提示用户按正确的键。而当用户按下 'Q' 键时,程序就会结束。

在这里,不需要等待用户输入,因为我并不要求用户输入,而是使用 getch,这个函数可以直接发送信息,而不需要按 ENTER 键。

我想在图形窗口中实现同样的功能,使用 Python 来做。

当用户按下 'W' 键时,相关的信息就应该显示出来。

我查找了 TkinterpyHook,但没有找到合适的思路,因为我找到的例子相对复杂。

我在这里想要的是一种方法,如何简化这个过程,其他的我可以自己生成代码。

对我来说,这里有两个重要的点:

 -> Keyboard press event must send a listener, and then, based on validations, appropriate messages must get diplayed.

 -> Until and unless, user does not press `'Q'`, the program should continue.

谢谢。

1 个回答

1

如果你想使用wxPython,那么你可能需要捕捉到键盘按下事件(EVT_KEY_DOWN)或者字符输入事件(EVT_CHAR)。另外一个可能的解决方案是查看加速器表(AcceleratorTable)。下面是一些相关的链接:

这里有一个绑定事件的典型例子:

self.panel.Bind(wx.EVT_KEY_DOWN, self.onKey)

然后在你的事件处理函数onKey中,你可以检查是哪个按键被按下,并根据这个来做出相应的操作。

撰写回答