使tkinter entry小部件跳转到fron的键盘快捷键

2024-06-28 11:21:36 发布

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

我正在使用tkinter entry小部件制作一个时间跟踪器,它允许我输入我正在做的任何活动,然后在csv文件中记录笔记和一天中的相应时间。我还使用键盘创建了一个键盘快捷键——“ctrl+q”,以便在python脚本运行时打开小部件。我的问题是,当“ctrl+q”在我的屏幕上打开/创建小部件时,我如何让“ctrl+q”使一个已经打开但在其他窗口后面的小部件跳到屏幕前面?这样一来,我将能够在第一时间打开小部件,如果已经使用相同的键盘快捷键打开,也可以使其可见

这是我试过的。当我运行这个程序时,点击“ctrl+q”将打开条目小部件,但是如果我在小部件的顶部放置另一个打开的窗口,再次点击“ctrl+q”并不会将其带到前面

while True: 
    try:  
        if keyboard.is_pressed('ctrl + q'):  
            def timenote(): # this gets the text entered into the entry widget, saves, the text and datetime to csv, displays both on the entry widget, and then clears the entry box
                timenotedict = {}
                Now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                mtext = time_entry.get()
                timenotedict[mtext] = Now
                label2text = Now + ' ' + mtext
                mlabel2 = Label(root, text= label2text).pack()
                with open('C:/Users/Me/Documents/timelog_test.csv', 'a', newline='') as csv_file:
                    writer = csv.writer(csv_file)
                    for key, value in timenotedict.items():
                        writer.writerow([key, value])
                mEntry.delete(0, END)

            root = Tk()
            time_entry = StringVar()

            root.geometry('250x100')
            root.title('Time Tracker')

            mlabel = Label(root, text = 'Timekeeping Note').pack()

            mbutton = Button(root, text = 'Log', command = timenote).pack()

            mEntry = Entry(root, textvariable = time_entry)

            mEntryPacked = mEntry.pack()

            #below is the problematic part

            try:

                if keyboard.is_pressed('ctrl + q'):
                     root.lift()
                else:
                     pass
            except:
                break

            root.mainloop()

        else:
            pass
    except:
        break

我对使用tkinter还很陌生,所以也许我遗漏了一些关于它在这里如何工作的信息?我也不是python方面的专家;我的任务是想出一种更简单的方法来跟踪工作中的时间,这是我的尝试,但这意味着我的代码很有可能在其他方面出现问题,而我缺少这些方面。任何想法都将不胜感激。谢谢


Tags: csvthetexttimeis部件时间root