2016-03-14 52 views
1

因此,我正在使用.place來設置我的小部件的位置。在tkinter中銷燬來自不同子例程的小部件

def printresults(): 
    SClabelspare=Label(cwindow, text ="Please enter the Customers ID Number:").place(x=10,y=560) 

我正在尋找調用另一個子例程,將銷燬這些小部件。我相信有一些叫.destroy()或.place_destroy?我不太清楚如何將這些工作,雖然我已經嘗試創建一個看起來像這樣:

def destroy_widgets(): 
    SClabelspare.destroy() 

,但它只是產生一個錯誤代碼,說NameError: global name 'SClabelspare' is not defined

任何幫助將不勝感激!

+0

不要爲格式化道歉,修復格式。 –

回答

1

首先,place()返回None,所以SClabelspare == None不是Tkinter ID。其次它是本地的,當函數退出時收集垃圾。你必須保持對許多方面可以完成的對象的引用。在進一步學習之前獲得基礎知識的Python教程將是一個不錯的主意https://wiki.python.org/moin/BeginnersGuide/Programmers此外,在不使用類結構的情況下編寫Tkinter應用程序是令人沮喪的體驗,除非它非常簡單。否則,你會得到像你一樣的錯誤,不得不花費很多的時間和精力來克服它們。這是我已經擁有的一個例子,目的是爲了對這個過程有一個大致的瞭解。

from Tkinter import * 
from functools import partial 

class ButtonsTest: 
    def __init__(self): 
     self.top = Tk() 
     self.top.title("Click a button to remove") 
     Label(self.top, text="Click a button to remove it", 
      bg="lightyellow").grid(row=0) 

     self.top_frame = Frame(self.top, width =400, height=400) 
     self.button_dic = {} 
     self.buttons() 
     self.top_frame.grid(row=1, column=0) 

     Button(self.top_frame, text='Exit', bg="orange", 
      command=self.top.quit).grid(row=10,column=0, columnspan=5) 

     self.top.mainloop() 

    ##-------------------------------------------------------------------   
    def buttons(self): 
     b_row=1 
     b_col=0 
     for but_num in range(1, 11): 
     ## create a button and send the button's number to 
     ## self.cb_handler when the button is pressed 
     b = Button(self.top_frame, text = str(but_num), 
        command=partial(self.cb_handler, but_num)) 
     b.grid(row=b_row, column=b_col) 
     ## dictionary key=button number --> button instance 
     self.button_dic[but_num] = b 

     b_col += 1 
     if b_col > 4: 
      b_col = 0 
      b_row += 1 

    ##---------------------------------------------------------------- 
    def cb_handler(self, cb_number): 
     print "\ncb_handler", cb_number 
     self.button_dic[cb_number].grid_forget() 

##=================================================================== 
BT=ButtonsTest() 
0

或者,如果這是應該很簡單,沒有大量的難以管理的全局變量,如果階級結構只會引入不必要的複雜性,你可以嘗試這樣的事情(它在命令行中爲python3解釋器工作):

from tkinter import * 
root = Tk() 

def victim(): 
    global vic 
    vic = Toplevel(root) 
    vicblab = Label(vic, text='Please bump me off') 
    vicblab.grid() 

def bumper(): 
    global vic 
    bump = Toplevel(root) 
    bumpbutt = Button(bump, text='Bump off', command=vic.destroy) 
    bumpbutt.grid() 

victim() 
bumper()