简体   繁体   English

TkInter所有按钮打开同一文件

[英]TkInter all buttons open same file

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. 它从配置文件中读取几个文件名(大部分为PDF),并为每个文件创建一个按钮,该按钮应使用默认应用程序打开文件。

The problem is, all buttons always open the last file in the config.ini file. 问题是,所有按钮始终打开config.ini文件中的最后一个文件。 This behaviour tells me something must be wrong with the for loop, but I don't know how to fix it. 此行为告诉我for循环一定有问题,但我不知道如何解决。

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. 使用i的当前值创建部分对象,而lambda在封闭范围内使用对变量i的引用,其值可以更改。 Or something like that. 或类似的东西。

I always find myself using partial with tkinter. 我总是发现自己与tkinter一起使用了部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM