2016-05-23 59 views
1

我在「實驗」與Tkinter的新東西(我與它一個初學者)和我做,只是爲了好玩很明顯,這個應用程序:刪除網格元素 - Tkinter的

from tkinter import * 

def text() : 
    if checking : 
     content.grid_forget() 
    else : 
     content = Label(root, text = txt.get()).grid(row = 3, column = 0) 

def check() : 
    checking = True 
    text() 

root = Tk() 

txt = StringVar() 
checking = False 

bt1 = Button(root, text = "Print me!", command = text) 
bt2 = Button(root, text = "Clear!", command = check) 
txt1 = Entry(root, textvariable = txt) 

row = 0 
for i in [bt1, bt2, txt1] : 
    i.grid(row = row, column = 0) 
    row+=1 

root.mainloop() 

我的問題是,爲什麼ISN 「清除」按鈕有效嗎?

+1

'checking'是check中的局部變量。 –

回答

1

您的應用有幾個問題,您可能需要考慮重新考慮結構和小部件管理。請考慮閱讀(http://effbot.org/tkinterbook/grid.htm)並檢查其他帖子,並確保您檢查@Bryan Oakley過去和現在的評論。

,因爲他提到你正在使用的局部變量,這是由它聲明爲全球如下容易修正:

global variable_name 
在你的代碼

另外,你可能要考慮重組內容( 「標籤」),當你將它添加到你的根窗口: 來自:

content = Label(root, text = txt.get()).grid(row = 3, column = 0) 

到:

content = Label(root, text = txt.get()) 
content.grid(row = 3, column = 0) 

,如果你不知道的是怎麼回事,請考慮添加打印()到你的代碼,這裏是一個快速片段:

def text() : 
    global content 
    print(root.grid_slaves()) 
    if checking : 
     content = Label(root, text = txt.get()) 
     content.grid(row = 3, column = 0) 

馬上就可以看到你每次點擊打印我,小工具被添加到您的佈局。爲您的佈局

最佳實踐(Best way to structure a tkinter application

快速提示:

def text() : 
    print(checking) 
    if checking : 
     content.grid_forget() 
    else : 
     content = Label(root, text = txt.get()).grid(row = 3, column = 0) 

def check() : 
    checking = True 
    text() 

root = Tk() 

txt = StringVar() 
checking = False 

檢查始終是假的... ...你可能會考慮重新思考一些邏輯以及

0

謝謝的答案是,我在應用程序中進行了更改,現在它效果很好!