Tkinter绑定不会调用函数

时间:2017-06-11 16:46:41

标签: python tkinter pyhook

我正在尝试更改tkinter条目小部件中的文本,作为用户输入的组合键(例如:ShiftL + ShiftR),python程序运行正常,但不会更改条目,为什么以及如何才能修理它? 我的GUI:

 # Program by Fares Al Ghazy started 20/5/2017
# Python script to assign key combinations to bash commands, should run in the background at startup
# Since this program is meant to release bash code, it is obviously non-system agnostic and only works linux systems that use BASH
# This is one file which only creates the GUI, another file is needed to use the info taken by this program

FileName  = 'BinderData.txt'
import tkinter as tk
from ComboDetect import ComboDetector

# Create a class to get pressed keys and print them
KeyManager = ComboDetector()


# Class that creates GUI and takes info to save in file

class MainFrame(tk.Tk):
    # variable to store pressed keys
    KeyCombination = ""

    def KeysPressed(self, Entry, KeyCombination):
        KeyCombination = KeyManager.getpressedkeys()
        Entry.delete(0, tk.END)
        Entry.insert(0, KeyCombination)

    # constructor

    def __init__(self, FileName, **kwargs):
        tk.Tk.__init__(self, **kwargs)
        # create GUI to take in key combinations and bash codes, then save them in file
        root = self  # create new window
        root.wm_title("Key binder")  # set title
        #  create labels and text boxes
        KeyComboLabel = tk.Label(root, text="Key combination = ")
        KeyComboEntry = tk.Entry(root)

        # Bind function to entry

        KeyComboEntry.bind('<FocusIn>',self.KeysPressed(KeyComboEntry, self.KeyCombination))

        KeyComboEntry.grid(row=0, column=1)
        ActionEntry.grid(row=1, column=1)
        # create save button
        SaveButton = tk.Button(root, text="save",
                               command=lambda: self.SaveFunction(KeyComboEntry, ActionEntry, FileName))
        SaveButton.grid(row=2, column=2, sticky=tk.E)


app = MainFrame(FileName)
app.mainloop()

和ComboDetect:

   #this program was created by LadonAl (Alaa Youssef) in 25.May.17
    #it detects a combination of pressed key and stores them in a list and prints the list when at least
    # one of the keys is released

import time
import pyxhook

class ComboDetector(object):
    def getpressedkeys(self):
        return self.combo

编辑:我已经更改了按键功能来测试它

 def KeysPressed(self, Entry, KeyCombination):
        Entry.config(state="normal")
        Entry.insert(tk.END, "Test")
        print("test")
        KeyCombination = KeyManager.getpressedkeys()
        Entry.delete(0, tk.END)
        Entry.insert(tk.END, KeyCombination)

这是我注意到的: 运行模块时,“test”将打印到控制台,不会发生任何其他情况。 当我尝试在条目小部件外单击并再次在其中单击时(退出焦点并重新输入),没有任何反应

1 个答案:

答案 0 :(得分:1)

问题在于,当您尝试绑定到KeyComboEntry时,您正在调用过程KeysPressed,而不是通过bind方法KeyComboEntry,您可以修复这可以通过使用KeyComboEntry.bind("<Key>", self.KeysPressed, KeyComboEntry, self.KeyCombination)来实现的。然后,绑定会使用KeysPressedKeyComboEntry的参数调用self.KeyCombination。另一种方法是使用lambda函数,就像您用于SaveButton一样,会计bind将事件传递给它。