2017-03-05 23 views
0

我有一個名爲'pages'的列表,它由多個框架x1到x5組成。我希望能夠通過使用tkraise()在它們之間導航。 x1框架只會在中心提供x2的下一個按鈕,x5只會在中心會有一個前一個按鈕,這會增加x4。幀x2到x4將會有下一個和上一個按鈕,這會相應地提升下一幀和上一幀,並且按鈕的位置將不得不調整,以便它們彼此相鄰。tkinter:使用帶有多個框架和功能的單個按鈕

使用只有一個上一個和下一個按鈕的for循環可以實現所有這一切嗎?我可以使用我的for循環獲取幀x2到x4中的上一個/下一個按鈕,但是我不確定要爲命令放置什麼,以便它們可以提高相應的前一幀/下一幀(我放在lambda旁邊)。願有人請幫忙。

from tkinter import * 

root = Tk() 

box = Frame(root) 
box.pack(fill=BOTH, expand=True) 
box.grid_columnconfigure(0, weight=1) 
box.grid_rowconfigure(0, weight=1) 

x1 = Frame(box, bg="gainsboro") 
x1.grid(row=0, sticky="nsew") 

x2 = Frame(box, bg="red") 
x2.grid(row=0, sticky="nsew") 

x3 = Frame(box, bg="blue") 
x3.grid(row=0, sticky="nsew") 

x4 = Frame(box, bg="green") 
x4.grid(row=0, sticky="nsew") 

x5 = Frame(box, bg="snow") 
x5.grid(row=0, sticky="nsew") 

frames = [x1, x2, x3, x4, x5] 

next_button = Button(frames[0], text="Next", command=lambda: frames[1].tkraise()) 
next_button.pack() 

previous_button = Button(frames[-1], text="Previous", command=lambda: frames[-2].tkraise()) 
previous_button.pack() 

for x in frames[1:4]: 
    next_button_2 = Button(x, text="Next", command=lambda: ?) 
    next_button_2.pack(side=RIGHT) 

    previous_button_2 = Button(x, text="Previous", command=lambda: ?) 
    previous_button_2.pack(side=LEFT) 

x1.tkraise() 

root.mainloop() 

回答

0

遍歷frames[1:4]將不能很好地工作在這裏,因爲它讓你有沒有簡單的方法來獲得下/上一幀。嘗試迭代指數來代替:

for i in range(1,4): 
    nb = Button(frames[i], text="Next", command=frames[i+1].tkraise) 
    nb.pack(side=RIGHT) 
    pb = Button(frames[i], text="Previous", command=frames[i-1].tkraise) 
    pb.pack(side=LEFT) 

注:不是lambda表達式,我剛剛設置的tkraise方法本身的命令。這是可能的,因爲它不需要參數。否則,你會遇到一個循環中的lambda表達式的常見問題:它們訪問的任何局部變量總是可以看到它們在循環的最後一次迭代期間的值。如果您想使用lambdas,則必須將i的值作爲參數捕獲:例如,lambda i=i: frames[i+1].tkraise()

事實上,這將是相當簡單的處理結束的情況下在同一個循環,從而節省自己有點重複代碼:

for i in range(len(frames)): 
    if i != len(frames) - 1: 
     nb = Button(frames[i], text="Next", command=frames[i+1].tkraise) 
     nb.pack(side=RIGHT) 
    if i != 0: 
     pb = Button(frames[i], text="Previous", command=frames[i-1].tkraise) 
     pb.pack(side=LEFT)