动态调整和添加Tkinter窗口小部件
我有一个用Python Tkinter做的图形界面,它会让用户输入文件名。我想在用户每次选择一个文件时,在窗口的其他地方添加一个输入框(Entry())。请问在Tkinter中可以做到这一点吗?
谢谢
马克
1 个回答
5
是的,这是可能的。你可以像添加其他小部件一样添加它——调用 Entry(...)
,然后使用它的 grid
、pack
或 place
方法来让它在界面上显示出来。
下面是一个简单的例子:
import Tkinter as tk
import tkFileDialog
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.button = tk.Button(text="Pick a file!", command=self.pick_file)
self.button.pack()
self.entry_frame = tk.Frame(self)
self.entry_frame.pack(side="top", fill="both", expand=True)
self.entry_frame.grid_columnconfigure(0, weight=1)
def pick_file(self):
file = tkFileDialog.askopenfile(title="pick a file!")
if file is not None:
entry = tk.Entry(self)
entry.insert(0, file.name)
entry.grid(in_=self.entry_frame, sticky="ew")
self.button.configure(text="Pick another file!")
app = SampleApp()
app.mainloop()