我在Python中製作了一個簡單的「程序啓動器」。我有一個製表符分隔文本文件,用,此刻,只是:Python tkinter按鈕回調意外行爲
記事本 C:\ WINDOWS \ NOTEPAD.EXE
寫 C:\ WINDOWS \ WRITE.EXE
程序讀取文本文件並創建一個對象數組。每個對象都有一個名稱屬性(例如記事本)和一個路由屬性(例如C:\ windows \ notepad.exe)。然後,對於每個對象,應該在按鈕上使用正確的名稱制作一個按鈕,然後單擊按鈕應該使用該路線執行正確的程序。
該程序非常接近工作。事實上,對象數組的形成是正確的,因爲for循環正確地打印出兩個不同的程序名稱和兩個不同的路線。問題是兩個按鈕雖然標記正確,但卻啓動了寫入程序!我相信問題出現在回調的某個地方,但是我的Python知識還沒有發展到足以解決這個問題!正如你可以從我的代碼中看到的,我嘗試了一個「內聯」回調,並且定義了一個「runprog」函數。他們都給出了相同的結果。
您的幫助,將不勝感激。
import Tkinter as tk
import subprocess
class MyClass:
def __init__(self, thename,theroute):
self.thename=thename
self.theroute=theroute
myprogs = []
myfile = open('progs.txt', 'r')
for line in myfile:
segmentedLine = line.split("\t")
myprogs.append(MyClass(segmentedLine[0],segmentedLine[1]))
myfile.close()
def runprog(progroute):
print(progroute)
subprocess.call([progroute])
root = tk.Tk()
button_list=[]
for prog in myprogs:
print(prog.thename)
print(prog.theroute)
button_list.append(tk.Button(root, text=prog.thename, bg='red', command=lambda: runprog(prog.theroute)))
# button_list.append(tk.Button(root, text=prog.thename, bg='red', command= lambda: subprocess.call(prog.theroute)))
# show buttons
for button in button_list:
button.pack(side='left', padx=10)
root.mainloop()
不太重複,但看到http://stackoverflow.com/questions/1107210/python-lambda-problems/1107333 –