2016-03-30 23 views
2

我正在寫一個Tkinter程序,我可以做出多個框架,我可以選擇他們相對於彼此的位置,所以我決定使用grid()來決定哪個框架在哪裏。我也有一個AppButton類創建一個按鈕/標籤/條目。我試圖在我想要創建按鈕的框架中傳遞,並使用網格來確定其相對於其創建框架的位置。Tkinter,一次做多個框架,每個框架中都有按鈕。但按鈕忽略他們給出的框架,只是使用網格

但是,當前按鈕無法制作在我試圖通過的框架中,而是它使用與框架相同的網格,並且只是放在那裏,回頭看起來很有意義。

我的問題是,我該如何改變這個按鈕的網格是一個單獨的網格相對於它所創建的框架?這樣,如果我移動框架,按鈕也會如此,但它們在框架中的相對位置保持不變。

現在框架和按鈕共享相同的網格,這就是他們的位置是如何確定的。

import Tkinter as tk 
import tkFileDialog as tkfd 

class AppButton: 
    #simple button construction 
    #create a button with chosen arguments 
    def create_button(self, words, rownum, frame): 
     btn = tk.Button(frame, text = words) 
     btn.grid(row = rownum, column = 2) 

    def create_entry(self, rownum, frame): 
     txt = tk.Entry(frame) 
     txt.grid(row = rownum, column = 1) 

    def create_label(self, words, rownum, frame): 
     lbl = tk.Label(frame, text = words) 
     lbl.grid(row = rownum, column = 0) 

    #input is composed of a Label, an Entry, and a Button. calls the three funcs above 
    def create_input(self, words, rownum, frame): 
     self.create_label(words, rownum, frame) 
     self.create_entry(rownum, frame) 
     self.create_button("OK", rownum, frame) 

class Application(tk.Frame): 
    """A GUI application that creates multiple buttons""" 

    #create a class variable from the root(master) called by the constructor 
    def __init__(self, master): 
     self.master = master 
     master.title("The best GUI") 
     tk.Frame.__init__(self, master, width=200, height=200) 
     self.grid(row = 0, column = 0) 

    def new_frame(self, master, color, row, column): 
     frame = tk.Frame(master, width=200, height=200, bg=color) 
     frame.grid(row = row, column = column) 
     return frame 


if __name__ == "__main__": 
    root = tk.Tk() 
    root.title("Button Test Launch") 
    app = Application(root) 
    appbutton = AppButton() 
    frame1 = app.new_frame(root, "red", 3, 1) 
    frame2 = app.new_frame(root, "blue", 2, 2) 
    appbutton.create_input("test1", 0, root) 
    appbutton.create_input("test2", 1, root) 
    appbutton.create_input("test3", 2, root) 
    appbutton.create_input("test4", 3, root) 
    root.mainloop() 

這裏是什麼樣子,現在的圖片: Current GUI

我期望的最終結果是有例如「測試1 ______ [OK]」要完全在這些框架的一個。

+0

運行你的代碼,我得到最後一行的紅色背景和倒數第二行的藍色背景。看起來你在測試過程中將'root','red','0,1'改爲'root','red',3,1'和''blue',0,2''改爲''blue',2,2' ,對嗎? – TigerhawkT3

回答

1

您正在告訴按鈕使用root作爲他們的父母。相反,你應該傳遞幀:

appbutton.create_input("test1", 0, frame1) 
appbutton.create_input("test2", 1, frame1) 
appbutton.create_input("test3", 2, frame2) 
appbutton.create_input("test4", 3, frame2)