python - 在循环中创建相互引用的 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()
解决方案
问题在于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]))
推荐阅读
- python - Python Jupyter Notebook Markdown - 设置水平分隔线的样式
- docker - Drone CI 无法使用私有存储库进行身份验证
- python - 如何解决错误 - python 的函数中未定义名称
- keyboard - 不能单写^
- javascript - 如何在模块公开的方法上设置监视器?
- google-sheets - Google表格:自动将新添加的单元格包含到现有公式中
- c# - 如何使用 C# Driver for MongoDB 反序列化只读字段?
- documentation - 对象签名的文档:“ ...命名参数的名称与变量名称不同”
- xamarin - Android 12.0 (S) 的 Xamarin 应用程序构建错误
- flutter - 如何在颤动的文本小部件中显示 SharedPreferences 值?