2013-07-20 38 views
0

我試圖創建一個簡單的應用程序用於說明目的。想法如下: 創建一個應用程序,該應用程序將運行僅與所選課程關聯的腳本文件(單選按鈕)。所以,我創建了列出主題的單選按鈕(點擊)。一旦選擇了主題,用戶必須按下Enter按鈕。這應該運行所選主題的所有.py文件(execute_script函數)。簡單的應用程序創建Python tkinter

但是,當我運行我的代碼時,我得到4個帶有'None'的messageboxes。點擊確定之後,我會看到一個只有enter按鈕的方形窗戶。我能做些什麼來糾正這個問題?

def check(file_name, relStatus): 
    radioValue = relStatus.get() 
    tkMessageBox.showinfo('You checked', radioValue) 
    been_clicked.append(file_name) 
    return 

def execute_script(): 
    for name in been_cliked: 
     subprocess.Popen(['python', 'C:\Users\Max\Subjects\{}'.format(name)]) 

    yield 


def main(): 

    #Create application 
    app = Tk() 
    app.title('Coursework') 
    app.geometry('450x300+200+200') 

    #Header 
    labelText = StringVar() 
    labelText.set('Select subjects') 

    #Dictionary with names 
    product_names = {} 
    names = [] 
    file_name = [] 
    names = ['Math', 'Science', 'English', 'French'] 
    file_name = ['calc.py', 'physics.py', 'grammar.py', 'livre.py'] 
    product_names = OrderedDict(zip(names, file_name)) 

    #Create radio buttons 
    global been_clicked 
    been_clicked = [] 
    relStatus = StringVar() 
    relStatus.set(None) 
    for name,file_name in product_names.iteritems(): 
     radio1 = Radiobutton(app, text=name, value=name, \ 
         variable=relStatus, command=check(file_name, relStatus)) 

    button = Button(app, text='Click Here', width=20, command=execute_script()) 
    button.pack(side='bottom', padx=15, pady=15) 

    app.mainloop() 


if __name__ == '__main__': main() 

回答

4

有你的腳本的幾個問題:

1)在你的execute_script()功能的錯字:for name in been_cliked

2)你實際上是調用當你創建你的收音機check()功能鈕釦。這就是爲什麼當你運行你的程序時你會看到彈出的窗口。

您需要更改此:

radio1 = Radiobutton(app, text=name, value=name, \ 
        variable=relStatus, command=check(file_name, relStatus)) 

這樣:

radio1 = Radiobutton(app, text=name, value=name, \ 
        variable=relStatus, command=check) 

查看如何check不再有括號?這意味着你傳遞函數名稱作爲參數,而不是實際上調用函數。當然,你會發現一個直接的問題是你不能再傳遞參數給你的回調函數!這是一個更大的問題。這裏有幾個鏈接,以幫助您開始:

這裏是解決方案:

更改此:

command=check(file_name, reStatus) 

這樣:

command = lambda: check(file_name, relStatus) 

3)你實際上沒有pack()你的單選按鈕在任何地方。在您的for循環中創建單選按鈕之後,添加類似如下內容:radio1.pack(side='top')

4)對於Click Here按鈕,您的回調有同樣的問題。你需要改變你的命令不調用該函數,而只是引用它:command = execute_script

5)在execute_script(),確保您import subprocessing

6)你確定你想yield,而不是returnexecute_script()功能?

7)在你所有的功能中,你需要確保been_clicked是全球性的。

我認爲如果你解決了這些問題,你會更接近獲得你要找的東西。祝你好運。!

+0

由於',command = execute_script()'是_calling_'execute_script',奇怪的是'for name in been_cliked'問題不會導致'NameError:全局名''was_cliked'未定義'錯誤。 – martineau

+0

我同意。原因是他有'yield'而不是'return'。使用'yield'不會導致'NameError'被引發。不知道這是爲什麼。 – Symmitchry

+1

啊,答案在這裏:http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained 'yield'會導致一個生成器被返回,但直到使用生成的代碼,代碼尚未運行。 – Symmitchry

相關問題