2015-09-24 63 views
0

在我的Python GUI腳本中,我有一個彈出窗口,並且彈出窗口上有文本區域小部件,用戶可以在其中輸入一些內容,然後單擊彈出窗口中的一個按鈕以獲取輸入文本。
但是,似乎在定義的函數中,彈出窗口上的小部件無法訪問。代碼去爲:
Python:如何訪問彈出窗口的小部件

from Tkinter import * 

def Add_Content(): 
    content = ent_new.get("1.0","end") 
    print content 

def Add_Task(): 
    task_index = 1 
    new_window = Toplevel() 
    label1 = Label(new_window, text="New Goal:") 
    label1.grid(row = 0, column = 0) 
    ent_new = Text(new_window, bg= "white", height=5, width= 30) 
    ent_new.grid(row=0,column =1,padx=5, pady=5) 
    bu_new = Button(new_window,text="Add", command = Add_Content) 
    bu_new.grid(row=0, column =2) 
    new_window.focus_force() 


master = Tk() 
group = LabelFrame(master, text="Operation", padx=5, pady=5, relief = RAISED) 
group.grid(row=0,column= 0, padx=10, pady=10, sticky=N) 
bu_add = Button(group, text = "Add Task",width = 15, command = Add_Task) 
bu_add.grid(row=0,column=0) 
mainloop() 
在上面的腳本

,該ent_new不能在功能Add_Content

回答

1

的問題是,ent_new是在另一個命名空間中。你可以把它傳遞給Button

bu_new = Button(new_window,text="Add", command = lambda: Add_Content(ent_new)) 
1

時使用的包裝功能(拉姆達)通過使Add_Content收到ent_new在這樣的論點解決它,

def Add_Content(my_ent): 
    content = my_ent.get("1.0","end") 
    print content 

,然後在不添加類和概念自我和父母,你可以在第一個答案中使用lambda,或者你可以使用全局變量。
注意:在python圈子中,全局變得相當皺眉,但他們工作並完成了工作。

from Tkinter import * 
global ent_new 

def Add_Content(): 
    content = ent_new.get("1.0","end") 
    print content 

def Add_Task(): 
    global ent_new 
    task_index = 1 
    new_window = Toplevel() 
    label1 = Label(new_window, text="New Goal:") 
    label1.grid(row = 0, column = 0) 
    ent_new = Text(new_window, bg= "white", height=5, width= 30) 
    ent_new.grid(row=0,column =1,padx=5, pady=5) 
    bu_new = Button(new_window,text="Add", command = Add_Content) 
    bu_new.grid(row=0, column =2) 
    new_window.focus_force() 


master = Tk() 
group = LabelFrame(master, text="Operation", padx=5, pady=5, relief = RAISED) 
group.grid(row=0,column= 0, padx=10, pady=10, sticky=N) 
bu_add = Button(group, text = "Add Task",width = 15, command = Add_Task) 
bu_add.grid(row=0,column=0) 
mainloop()