首页 > 解决方案 > 在循环中创建相互引用的 Tkinter 按钮

问题描述

我正在尝试创建一系列带有循环的 tkinter 按钮,这些按钮是 .grid'd 到它们各自的框架。我希望每个按钮都有一个 .tkraises 我创建的帧列表中的下一帧的功能。知道怎么做吗?这就是我所拥有的。我认为创建了按钮/框架,但 .tkraise 功能不起作用。谢谢

from tkinter import *
from PIL import ImageTk, Image

## Define root and geometry
root = Tk()
root.geometry('200x200')

# Define Frames
winlist = list()
winlist = Frame(root, bg='red'), Frame(root, bg='green'), Frame(root, bg='blue')

# Configure Rows
root.grid_rowconfigure(0, weight = 1)
root.grid_columnconfigure(0, weight = 1)

# Place Frames
for window in winlist:
    window.grid(row=0, column = 0, sticky = 'news')

# Raises first window 'To the top'
winlist[0].tkraise()

# Function to raise 'window' to the top
def raise_frame(window):
    window.tkraise()

d = {}
count = 0
for x in range(0, 3):
    d["label{0}".format(x)] = Label(winlist[x], text = "label{0}".format(x))
    if count <=1:
        try:
            d["button{0}".format(x)] = Button(winlist[x], text = "button{0}".format(x), command = raise_frame(winlist[x+1]))
            d["button{0}".format(x)].pack(side=TOP)
        except:
            pass
    else:
        d["label{0}".format(x)].pack(side=TOP)
    count += 1

root.mainloop()

标签: pythontkinter

解决方案


问题在于command该行的选项:

d["button{0}".format(x)] = Button(winlist[x], text = "button{0}".format(x), command = raise_frame(winlist[x+1]))

它将raise_frame(winlist[x+1])立即执行,然后将结果(即None)分配给command选项。因此,稍后单击该按钮不会执行任何操作。

您需要lambda改用:

d["button{0}".format(x)] = Button(winlist[x], text="button{0}".format(x),
                                  command=lambda x=x: raise_frame(winlist[x+1]))

推荐阅读