我有一个可以在Ubuntu系统中完美运行的代码。这只是基于它的最少代码:
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()
[当我在Ubuntu机器上运行时,我可以看到我按下的Control
键(向左或向右控件)正确绑定,因为我看到了打印效果和预期的视觉效果。另一方面,在Mac上运行相同的代码,我看不到打印输出,当然也不会出现预期的结果。
我跟随this文档执行绑定。我不是在尝试使用Mac的Command
键,而是常规的左Control
键。
不同系统的出价代码是否不同?这没有道理,但我找不到问题。
有三种不同类型的键:
普通键;例如:s,a,1,9和...
标点符号;例如'Left','Up','bracketright'(']'),! ,%和...
特殊键;例如:
# bind and show a key press event with Tkinter
from tkinter import *
root = Tk()
prompt = ' Press any key '
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
def key(event):
if event.char == event.keysym:
msg = 'Normal Key %r' % event.char
elif len(event.char) == 1:
msg = 'Punctuation Key %r (%r)' % (event.keysym, event.char)
else:
msg = 'Special Key %r' % event.keysym
label1.config(text=msg)
root.bind_all('<Key>', key)
root.mainloop()
上面的代码说明了一切;)