0

I've build a simple tool to search for files in a MySQL database, the results should be displayed in a tkinter textfield as a hyperlink. So far so good but everytime I click on a link it only opens the last displayed hyperlink. I think the problem is that the function openPDF() is called after the for loop already ended, when the function openPDF(newpath) is called, the variable newpath has the value of the last path displayed in the textfield. I have no idea how to fix this.

I appreciate every bit of help i can get.

erg = cursor.fetchall()

path = '\\\\path\\to\\folder\\'

for pdf in erg: 

    print 'Found files: %s\n' % pdf
    print pdf
    newpath = path + '%s' % erg[i]
    text.insert(END, pdf, hyperlink_path.add(lambda: openPDF(newpath)))
    text.insert(END, '\n')
    print pdf

The Hyperlink Manager Class

from Tkinter import *

class HyperlinkManager:

    def __init__(self, text):

    self.text = text

    self.text.tag_config("hyper", foreground="blue", underline=1)

    self.text.tag_bind("hyper", "<Enter>", self._enter)
    self.text.tag_bind("hyper", "<Leave>", self._leave)
    self.text.tag_bind("hyper", "<Button-1>", self._click)

    self.reset()

def reset(self):
    self.links = {}

def add(self, action):
    # add an action to the manager.  returns tags to use in
    # associated text widget
    tag = "hyper-%d" % len(self.links)
    self.links[tag] = action
    return "hyper", tag

def _enter(self, event):
    self.text.config(cursor="hand2")

def _leave(self, event):
    self.text.config(cursor="")

def _click(self, event):
    for tag in self.text.tag_names(CURRENT):
        if tag[:6] == "hyper-":
            self.links[tag]()
            return

Function: openPDF()

def openPDF(pdf_file):

    print(pdf_file)

    if platform.system() == 'Linux':
        subprocess.call(["xdg-open", pdf_file])
    else:
        #Windows
        subprocess.Popen([pdf_file],shell=True)
Bryan Oakley
  • 341,422
  • 46
  • 489
  • 636
TKuehn
  • 1
  • Possible duplicate of [Tkinter assign button command in loop with lambda](http://stackoverflow.com/questions/17677649/tkinter-assign-button-command-in-loop-with-lambda) – Lafexlos Feb 20 '17 at 15:03
  • Or any of these: [Why do my lambda functions or nested functions created in a loop all use the last loop value when called?](http://sopython.com/canon/30/why-do-my-lambda-functions-or-nested-functions-created-in-a-loop-all-use-the-las/) – Lafexlos Feb 20 '17 at 15:03

0 Answers0