2012-03-18 59 views
0

Tkinter(使用Python 2.5.1)看到的問題是,當我使用grid()方法添加元素時,它們堆疊在彼此之上而不是創建新行。代碼將運行,但部件都堆疊在應用程序中心的兩行中。這是爲什麼發生?Tkinter Widgets將被堆疊

from Tkinter import * 

import random 

class Application(Frame): 
    """Define Application's constructor""" 
    def __init__(self, master): 
     """Initialize the Frame""" 
     Frame.__init__(self, master) 
     self.grid() 
     self.create_widgets() 


    #Create the widgets 
    def create_widgets(self): 
     self.lblTitle = Label(self, text="Build Your Own Burger") 
     self.lblTitle.grid(row=0) 

     self.lblBurgerImg = Label(self, image=PhotoImage(file="burger.gif")) 
     self.lblTitle.grid(row=1) 

     self.lblName = Label(self, text="Name:") 
     self.lblName.grid(row=2, column=0, columnspan=2, sticky=W) 

     self.entryName = Entry(self) 
     self.entryName.grid(row=2, column=1, columnspan=2, sticky=W) 

     self.lblToppings = Label(self, text = "Toppings:") 
     self.lblTitle.grid(row=3, column=0, sticky=W, columnspan=5, sticky=W) 

     self.chkCheese = Checkbutton(self, text="cheese") 
     self.chkCheese.grid(row=3, column=1, sticky=W, columnspan=5, sticky=W) 


#main program 

#create a root window 
root = Tk() 

#assign a title for the GUI 
root.title("Order Up!") 

#Define size of root window 
root.geometry("700x700") 

#create an instance of your application 
app = Application(root) 

#start the event loop 
root.mainloop() 

回答

2

首先,你一定代碼對你的作品?我在兩條線路上遇到了有關使用sticky選項兩次的錯誤。但這不是問題。

您認爲發生的並不是實際發生的事情。這些小部件不是「全部」堆疊在一起:兩個是不可見的,因爲您沒有調用其上的grid方法,而只是標題堆疊在另一個小部件的頂部,因爲那是您放好它。

問題是您撥打self.lblTitle.grid(...)三次。其中兩次你無疑打算在其他小部件上調用grid方法。

+0

哇,我不敢相信我沒有接受。謝謝,布萊恩!修復後,我現在看到一個空白空間,我的漢堡圖像應該是。它是一個與python腳本位於同一目錄中的.gif文件。我需要添加任何代碼才能正確顯示它嗎? – KongMD 2012-03-18 11:08:07

+0

原來我只是需要單獨聲明圖像並添加寬度和高度屬性。再次感謝 :) – KongMD 2012-03-18 14:20:14