Thomas Armin Leitgeb
Thomas Armin Leitgeb

Reputation: 21

Tkinter Key bindings not working

I am currently working on a smal Projekt for my glider. The Tkinter app should autostart with RPi and either open an app called XCSOAR or just simply quit. It is working with the buttons, but since I wont have a mouse with me in the plane I need to bind it to keys. It's already working on windows, but not on my raspberry pi. I guess its a problem with the focus?

from Tkinter import *
import os

class MainWindow:

    def __init__(self, master):
        frame = Frame(master)
        master.configure(background="white")
        master.overrideredirect(True)
        master.geometry("{0}x{1}+0+0" .format(root.winfo_screenwidth(), root.winfo_screenheight()))
        master.bind("<Up>", self.xcsoar1)
        master.bind("<Down>", self.startx1)
        frame.pack()

        photo1=PhotoImage(file="XCS.gif")
        self.button1 = Button(frame, image=photo1, command = self.xcsoar, background="white")
        self.button1.image = photo1
        self.button1.pack()

        photo3=PhotoImage(file="center.gif")
        self.center = Label(frame, image = photo3, background="white")
        self.center.image = photo3
        self.center.pack()

        photo2=PhotoImage(file="RPi.gif")
        self.button2 = Button(frame, image=photo2, command = self.startx, background="white")
        self.button2.image=photo2
        self.button2.pack()

    def xcsoar(self):
        os.system('xcsoar.exe')
        root.destroy()
    def startx(self):
        root.destroy()

    def xcsoar1(self, event):
        os.system('xcsoar.exe')
        root.destroy()
    def startx1(self, event):
        root.destroy()

root = Tk()
b = MainWindow(root)
root.mainloop()

any ideas?

Upvotes: 2

Views: 3085

Answers (2)

user14173492
user14173492

Reputation:

I had the same problem, but i don't know if this works for you, but try add force focus before the keybind

def __init__(self, master):
        frame = Frame(master)
        master.configure(background="white")
        master.overrideredirect(True)
        master.focus_force() ######
        master.geometry("{0}x{1}+0+0" .format(root.winfo_screenwidth(), root.winfo_screenheight()))
        master.bind("<Up>", self.xcsoar1)
        master.bind("<Down>", self.startx1)
        frame.pack()

i add ##### just to mark where it is

Upvotes: 2

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19144

Please read about MCVEs. The advice is good not only for posting, but for development and debugging. What follows is stripped down version of your code with the essential key bindings.

import tkinter as tk
root = tk.Tk()

def up(event): print('up')
def dn(event): print('dn')

root.bind('<Up>', up)
root.bind('<Key-Down>', dn)
root.mainloop()

This works when run from an IDLE editor on 3.5.1, Win10. Pressing either Up or Down keys result in a print to the IDLE shell. How about on your computer? How about on your RPi?

Upvotes: 1

Related Questions