Struggling with binding on tags in tkiner text widget

后端 未结 1 915
清酒与你
清酒与你 2021-01-29 12:22

I\'m struggling a bit with the text widget in the tkinter module. I have added tags that I try to bind a function to.

Regardless of how I type it, it happens one of two

相关标签:
1条回答
  • 2021-01-29 12:39

    Consider this code:

    self.tekstfelt.tag_bind(setning, "<Button-1>", self.utskrift2(start))
    

    It has the same behavior as this code:

    result = self.utskrift2(start)
    self.tekstfelt.tag_bind(setning, "<Button-1>", result)
    

    Do you see the problem? You need to pass a callable to the binding, and your function isn't returning a callable.

    The solution is to use something like lambda or functools.partial. I prefer lambda mainly because it doesn't require an extra import. Using lambda, you need for the function to accept the event passed by tkinter, and you also need to pass in the start value. It would look something like this:

    self.tekstfelt.tag_bind(setning, "<Button-1>", lambda event, start=start: self.utskrift2(start))
    

    Since you are calling utskrift2 with a single argument, and that argument is the start value rather than the event, you need to redefine utskrift2 to look like this:

    def utskrift2(self, start):
        if start == 0:
            print("Taggen til første linjen")
        if start == 1:
            print("Taggen til andre linjen")
        if start == 2:
            print("Taggen til tredje linjen")
    
    0 讨论(0)
提交回复
热议问题