让我们说我有一个Tkinter应用程序,其中2行显示2个小部件:
from tkinter import *
from tkinter.ttk import *
root = Tk()
Label(root, text="Some Data").grid(row=0)
Label(root, text="Some Data").grid(row=1)
root.mainloop()
现在这将在row0和row1上显示两个小部件。 现在,如果我想在稍后阶段在这两行之间插入另一个(一个或多个)小部件(比如作为对按钮单击事件的响应),那么最好的方法是什么。
当前输出:
Some Data
Some Data
预期产出:
Some Data
<<New data>>
Some Data
<<New Data>>
将在稍后阶段插入,作为对按钮点击的响应。
<<New Data>>
可能是一行或多行。
答案 0 :(得分:2)
我确实有一个简单的解决方案。
如果您希望稍后插入窗口小部件,并且您知道自己就可以将第2个标签放在网格第2行,然后将新窗口小部件放在网格第1行。如果您需要多行,则可以将第二个标签放在更远的位置。
from tkinter import *
from tkinter.ttk import *
root = Tk()
def add_new_data():
Label(root, text="<<New Data>>").grid(row=1)
Label(root, text="Some Data").grid(row=0)
Label(root, text="Some Data").grid(row=2)
Button(root, text="Add New Data", command=add_new_data).grid(row=3)
root.mainloop()
结果:
[![在此处输入图像说明] [1]] [1] [![此处输入图像说明] [2]] [2]
这样做的原因是因为如果没有任何内容,Tkinter的几何管理器会将行和列折叠为空,这样你就可以在使用这种行为时利用这种行为。
Now if you wanted something that could work with any number of label then we can use a list to help us accomplish that.
My next example with be written in class and will show the use of a list to do what we want.
We can store widgets in a list and because we can do this we are also able to decide where in that list to put stuff and use the lists index to our advantage when setting up the grid.
First thing is to create our `Some Data` labels and append them to a list. The next is the add the button to that list at the end of the list. This button we will used to call a class method that will `insert()` a new label into our list.
Next that same method will forget the grid for all widgets inside of our label frame and then it will perform a `for` loop over the list and re add all the old widgets and the new one in the correct order.
Take a look at the below example.
import tkinter as tk
class App(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self.master = master
self.label_frame = tk.Frame(self.master)
self.label_frame.grid()
self.label_list = []
for i in range(2):
self.label_list.append(tk.Label(self.label_frame, text="Some Data"))
self.label_list[i].grid(row=i)
self.label_list.append(tk.Button(self.label_frame, text="Add new data", command=self.add_new_data))
self.label_list[2].grid(row=2)
def add_new_data(self):
self.label_list.insert(1, tk.Label(self.label_frame, text="<<New Data>>"))
for widget in self.label_frame.children.values():
widget.grid_forget()
for ndex, i in enumerate(self.label_list):
i.grid(row=ndex)
if __name__ == "__main__":
root = tk.Tk()
my_app = App(root)
root.mainloop()
Results:
[![enter image description here][3]][3]
We can add as many new labels as we like.
[1]: https://i.stack.imgur.com/zZ5TY.png
[2]: https://i.stack.imgur.com/yw9fd.png
[3]: https://i.stack.imgur.com/Ck26J.png