José Chamorro
José Chamorro

Reputation: 547

How do I close a tkinter mainloop by pressing some keyboard key

I would like to ask about two related issues. The main one:

I want to open an entry, type some text, and then I want the program to resume when I press the Enter key.

However, the only solution I've found to shot down tk mainloop is adding an 'ok' buttom which I most click on.

As the idea is to use the quick pop up window to retrive some information and move one, the clicking requirement is very unfortunate.

The second issue is:

I would like the entry box to pop up in front of everything else on my screen... is that possible? I'm pretty new on programming so I haven't look into the second issue. I use Jupyter notebook to run this code, I don't know if I should compile my code for it to better interact with the user's interface.

Thanks!

master = tkinter.Tk()
e = tkinter.Entry(master)
e.pack()
def callback():
    global fa
    fa=e.get() # This is the text you may want to use later
    master.destroy()
b = tkinter.Button(master, text = "OK", width = 10, command = callback)
master.mainloop()

No error in that code. Global variable 'fa' is created and then the mainloop is 'destroyed'. The problem, as said, is that it requires the user to click on the ok buttom

Upvotes: 1

Views: 464

Answers (1)

RIPPLR
RIPPLR

Reputation: 316

This is just some basic tkinter binding. When you press an arrow key, the triangle moves. Hope this helps.

from tkinter import *
from tkinter import Canvas

tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
canvas.create_polygon(10, 10, 10, 60, 50, 35, fill='blue')  # This is the triangle


def movetriangle(event):
    if event.keysym == 'Up':
        canvas.move(1, 0, -3)
    elif event.keysym == 'Down':
        canvas.move(1, 0, 3)
    elif event.keysym == 'Left':
        canvas.move(1, -3, 0)
    elif event.keysym == 'Right':
        canvas.move(1, 3, 0)
canvas.bind_all('<Key>', movetriangle)
tk.mainloop()

Upvotes: 1

Related Questions