我想用Tkinter做一个键盘快捷操作命令。键盘事件会调用一个函数:当我按下'b'
时,执行函数'buy'
,当我按下 's'
时,执行函数 'sell'
。但是我的 GUI 中有一个条目。当我在这个条目中输入一个数字时,我将按'b' 调用函数 'buy'
或按 's'
调用函数 'sell'
。当然,该条目将显示 'b'
或 's'
。我想在按下 's'
或 'b'
时调用函数,并且条目只会区分和显示数字。我怎样才能达到这个目的?
这是我的代码:
# -*- coding: utf-8 -*-
from Tkinter import *
import tkFont
import datetime
class TradeSystem(object):
"""docstring for TradeSystem"""
def __init__(self):
self.root = Tk()
self.root.geometry('465x180')
self.root.resizable(width=True, height=False)
Label(self.root, text = 'Volume',font = tkFont.Font(size=15, weight='bold')).grid(row=0, column=0)
self.e1_str = StringVar()
self.e1 = Entry(self.root,bg = '#D2E48C',width = 10,textvariable = self.e1_str)
self.e1.grid(row = 1, column = 0)
self.v = IntVar()
self.Cb = Checkbutton(self.root,variable = self.v,text = 'Keyboard active',onvalue = 1,offvalue = 0,command = self.Keyeve)
self.Cb.grid(row = 3,column = 0)
self.currenttime = StringVar()
Label(self.root,textvariable = self.currenttime).grid(row=4, column=0,sticky = NW)
self.t_loop()
self.root.mainloop()
def buy(self,event):
print 'This is buy function.'
def sell(self,event):
print 'This is sell function.'
def rb(self):
self.root.bind('<KeyPress-b>',self.buy)
self.root.bind('<KeyPress-s>',self.sell)
def Keyeve(self):
if self.v.get():
self.rb()
else:
self.root.unbind('<KeyPress-b>')
self.root.unbind('<KeyPress-s>')
def t_loop(self):
self.currenttime.set(datetime.datetime.now().strftime("%Y-%m-%d,%H:%M:%S"))
self.root.after(1000,self.t_loop)
if __name__ == '__main__':
TradeSystem()
我在条目 self.e1
中输入了一些数字,当 keyboard active
为 'on'
时,我按下 ' b'
调用函数 'buy'
,例如:
函数 'buy'
起作用了。
我只是想让条目区分数字,当我输入数字后按'b'
时,立即调用'buy'功能。我该如何实现?
最佳答案
使用修饰键将文本输入与命令热键分开,例如 Ctrl:
self.root.bind('<Control-b>',self.buy)
self.root.bind('<Control-s>',self.sell)
self.root.bind('<Control-B>',self.buy)
self.root.bind('<Control-S>',self.sell)
请注意,上面已经绑定(bind)了大写和小写键,因此如果 Caps Lock 打开,它仍然有效。
关于python - 如何避免 python Tkinter 中的键盘冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34634809/