2014-01-22 52 views
0

我想要一個文件在我的tkinter GUI中的按鈕上打開。但是,聲音文件在我的程序運行時播放(如同馬上)並且在按下按鈕時不起作用。這裏是我的代碼:如何使用Tkinter按鈕控制文件打開?

####Imports 
    import os 
    import sys 
    from tkinter import * 

    ####definitions 
    def blackobj(): 
     from os import startfile 
     startfile ('simon_objection.mp3') 

    ####Window 
    mGui = Tk() 
    mGui.geometry ('1280x720+100+50') 
    mGui.title ('Gui App') 
    mGui.configure(background='blue') 

    ####Labels 
    #Title 
    wlabel = Label(text = "Welcome to the Ace Attorney Soundboard!", font = 'georgia',fg ='white', bg = 'blue').place(x=0,y=0) 
    objectionheader = Label (text = 'Objections:', font = 'georgia', fg = 'white', bg = 'blue',).place (x=0,y=45) 

    ####Buttons 
    objblackquill = Button (mGui, text = 'Blackquill', font = 'georgia', command =blackobj()).place (x=0,y=75) 

    mGui.mainloop() 

有我在我的代碼犯了一個錯誤還是我需要添加別的東西來獲取聲音時按下按鈕的工作,而不是在腳本運行時?

感謝

回答

3
objblackquill = Button (mGui, text = 'Blackquill', font = 'georgia', command =blackobj()).place (x=0,y=75) 

你的問題是與上面的線。當Python讀取您的代碼時,它會看到blackobj(),它將其解釋爲有效的函數調用。所以,它執行它。


爲了解決這個問題,你可以使用一個lambda「隱藏」的號召,blackobj它自己的函數中:

objblackquill = Button (..., command=lambda: blackobj()).place (x=0,y=75) 

但是,因爲你沒有經過blackobj任何參數,一個更好的解決方法就是去掉括號:

objblackquill = Button (..., command=blackobj).place (x=0,y=75) 

另外,tkinter.<widget>.place始終返回None,因此應在其自己的行上調用。

換句話說,每一行這樣寫的:

wlabel = Label(...).place(x=0,y=0) 

應該寫成這樣:

wlabel = Label(...) 
wlabel.place(x=0,y=0) 
+0

除非你不需要做你的對象什麼了,其中情況下,不要將它們分配給一個變量。我總是用'Labels'作爲我的'Entry'字段。 'date = StringVar(); e_date = ttk.Entry(根,textvariable =日期); e_date.grid(行= 1,列= 2); ttk.Label(root,text =「Date:」)。grid(row = 1,column = 1' –

+0

非常感謝!這解決了我遇到的問題,額外的建議非常感謝! – Snubb