我有一个在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
。
不同的系统是否有不同的招标代码?这没有意义,但我找不到问题。
答案 0 :(得分:0)
共有三种不同类型的键:
普通键;例如: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()
上面的代码说明了一切;)