I've written this little program. It reads a couple of file names (PDF mostly) from a config file and creates a button for each file which should open the file using the default application.

The problem is, all buttons always open the last file in the config.ini file. This behaviour tells me something must be wrong with the for loop, but I don't know how to fix it.

Any ideas?

from tkinter import *
import subprocess, os, sys

def opendoc(file):
    if sys.platform == 'linux':
        subprocess.call(["xdg-open", file])
    else:
        os.startfile(file)

ini = open('config.ini')
carray = []

for line in ini:
    carray.append(line)

for line in carray:
    print(line)

master = Tk()

for i in carray:
    Button(master, text=i, command=lambda: opendoc(i)).pack(anchor=W)

mainloop()
有帮助吗?

解决方案

Maybe try

from functools import partial

and use

Button(master, text=i, command=partial(opendoc, i))

The partial object is created using the current value of i, whereas the lambda uses a reference to the variable i in the enclosing scope, whose value can change. Or something like that.

I always find myself using partial with tkinter.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top