Python 启动时运行按钮命令
我目前正在开发一个程序来扫描一个文件夹,找到所有的.exe文件,并将它们放在一个列表中准备运行 到目前为止,我已经成功地获得了列表,创建了按钮,但没有运行程序本身。相反,它是在打开运行python代码时运行程序Python 启动时运行按钮命令,python,button,tkinter,command,startup,Python,Button,Tkinter,Command,Startup,我目前正在开发一个程序来扫描一个文件夹,找到所有的.exe文件,并将它们放在一个列表中准备运行 到目前为止,我已经成功地获得了列表,创建了按钮,但没有运行程序本身。相反,它是在打开运行python代码时运行程序 import os import Tkinter top = Tkinter.Tk() def run(exe): os.system(exe) exes = [] for root, dirs, files in os.walk(r'./'): for file
import os
import Tkinter
top = Tkinter.Tk()
def run(exe):
os.system(exe)
exes = []
for root, dirs, files in os.walk(r'./'):
for file in files:
if file.endswith('.exe'):
exes.append(file)
def dispgames(exes):
exes = exes[:-4]
return exes
def runit(game):
os.system(game)
#print(exes)
#print(dispgames(exes))
def radioCreate(typeArray):
for t in typeArray:
b = Tkinter.Button(top, text = dispgames(t), command=runit(t))
b.pack()
radioCreate(exes)
Tkinter.Button(top, text = "Display").pack()
top.mainloop()
任何帮助都将不胜感激。
命令
需要函数名-它意味着没有()
和参数
可以使用lambda
执行此操作
command=lambda:runit(t)
但是您在for
循环中创建它,因此t
可能会出现问题
lambda
引用t
,而不是从t
复制的值-因此在循环中创建的所有lambda
将使用相同的值-分配给t
的最后一个值
但您可以将值从t
复制到lambda
command=lambda x=t:runit(x)
-
command=runit(t)
表示“运行函数runit(t)
并将结果分配给command
”。有时它是有用的
-
顺便说一句:在Tkinter
bind()
和after()
中,也需要函数名。请格式化所有代码,而不是第一行。对不起,我不知道如何使用这里的代码段函数,有点困惑。我现在已经整理好了。:)非常感谢。这有点帮助。我已经用文件夹“test1.exe”和“test2.exe”中的两个程序尝试过了。当我单击test1.exe的按钮时,它正在运行test2.exe,但是test2.exe的按钮正常工作。如果在for
循环中使用lambda:runit(t)
,那么所有lambda都使用相同的值-因为它们使用对内存中相同位置的引用,该位置的最后一个值已分配给t
(test2.exe
)。如果使用lambda x=t:runit(x)
,则x=t
将从t
复制值,并且每个lambda在x
中具有不同的值。