[Python] Binding keys in Mac OS X - Tkinter

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a code that works perfect in a Ubuntu system. This is just a minimal code based on it:

    import tkinter as Tk
    import tkFileDialog
    import ttk

    class AppGUI(Tk.Frame):

    def __init__(self, parent):
    self.ctrl = False
    self.parent = parent
    self.centerWindow()
    self.initGUI()
    self.plot()

    def initGUI(self):
    # Notebooks
    self.notebook = ttk.Notebook(self.parent)
    self.frame_one = Tk.Frame(self.notebook) # first page
    self.frame_two = Tk.Frame(self.notebook) # second page
    self.notebook.add(self.frame_one, text='Notebook 1')
    self.notebook.add(self.frame_two, text='Notebook 2')
    self.notebook.pack(side = Tk.TOP, fill="both", expand=True)

    # Realization frame
    self.out_frame = Tk.Frame(self.parent, bd=1, relief=Tk.SUNKEN)
    self.out_frame.pack(side=Tk.TOP, fill="both", expand=True)

    # Key events
    self.key()

    def centerWindow(self):
    w = 800
    h = 800

    sw = self.parent.winfo_screenwidth()
    sh = self.parent.winfo_screenheight()

    x = (sw - w)/2
    y = (sh - h)/2
    self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))


    def key(self):
    # Key events
    def press(event):
    self.ctrl = True
    def release(event):
    self.ctrl = False

    self.parent.bind('<Control_L>', press)
    self.parent.bind('<KeyRelease-Control_L>', release)

    def plot1(self):
    f = plt.figure(figsize=(1, 1), dpi=300)
    c_plot1 = FigureCanvasTkAgg(f, master=self.frame_one)
    c_plot1.show()
    c_plot1.pack(side=Tk.LEFT, fill="both", expand=True)

    def onClickPlot1(event):
    if event.inaxes is not None:
    if self.ctrl:
    print "Control key pressed"
    # Do my stuff

    c_plot1.mpl_connect('button_press_event', onClickPlot1)

    def plot2(self):
    # Same stuff for plot 2

    def plot(self):
    self.plot1()
    self.plot2()


    def main():
    root = Tk.Tk()
    app = AppGUI(root)
    root.mainloop()


    if __name__ == '__main__':
    main()


    When I run thin in a Ubuntu machine, I can see that whatever Control key I press (left or right control) is correctly binded, as I see the print and the expected visual result. Running the same code in a Mac, on the other hand, I cannot see the print output and, of course, the expected result doesn't happens.

    I followed this document to perform the binding. I'm not trying to use the Mac Command key, just the regular left Control.

    Are there different biding codes for different systems? This doesn't make sense, but I can't find the problem.

    Continue reading...

Compartilhe esta Página