本篇文章主要讲解,python动态加载tkinter元素的方法
日期:2022年6月2日
作者:任聪聪
利用tkinter做动态的表单界面实际上是很简单的,只需要对界面进行update即可实现,每一个元素实际上都可动态加载。
动态加载表单元素labe标签
实际效果:
代码实例:
import tkinter
import tkinter.messagebox as messagebox
#声明首页
class homePage:
def __init__(self, windows):
self.windows = windows
self.windows.title("tkinter做动态表单的demo")
self.windows.geometry('500x500')
self.windows.configure(background='#ffffff')
self.pageContent()
#页内函数
def pageContent(self):
#显示标签表单
self.runLableBtn = tkinter.Button(self.windows,width=70, height=1, text="执行输出标签", bg="#F0F0F0",
command=self.runLable)
self.runLableBtn.grid(row=5)
# 执行
def runLable(self):
lable_row =6
input_row =7
for i in range(0,10):
number = str(i)
if i>0:
# 按规则增加间距
lable_row += 2
input_row += 2
self.txt_input_lable = tkinter.Label(self.windows, height=2, text="标签"+number)
self.txt_input_lable.grid(row=lable_row, column=0, rowspan=1, sticky="W")
self.txt_input = tkinter.Text(self.windows, width=70, height=2, fg="black", bg="white")
self.txt_input.grid(row=input_row, column=0)
self.windows.update()
def start_home():
windows = tkinter.Tk()
homePage(windows)
windows.mainloop()
start_home()
动态的内容展示
效果说明:
代码实例:
import tkinter
import tkinter.messagebox as messagebox
#声明首页
class homePage:
def __init__(self, windows):
self.windows = windows
self.windows.title("tkinter做动态表单的demo")
self.windows.geometry('500x500')
self.windows.configure(background='#ffffff')
self.pageContent()
#页内函数
def pageContent(self):
#显示标签表单
self.runLableBtn = tkinter.Button(self.windows,width=70, height=1, text="展示列表", bg="#F0F0F0",
command=self.runLable)
self.runLableBtn.grid(row=5)
# 执行
def runLable(self):
lable_row =6
for i in range(0,10):
number = str(i)
if i>0:
lable_row += 2
self.txt_input_lable = tkinter.Label(self.windows, height=2, text="list:"+number)
self.txt_input_lable.grid(row=lable_row, column=0, rowspan=1, sticky="W")
self.windows.update()
def start_home():
windows = tkinter.Tk()
homePage(windows)
windows.mainloop()
start_home()
给text框写入新的内容
效果展示:
代码实例:
import tkinter
import tkinter.messagebox as messagebox
import time
#声明首页
class homePage:
def __init__(self, windows):
self.windows = windows
self.windows.title("tkinter做动态表单的demo")
self.windows.geometry('500x500')
self.windows.configure(background='#ffffff')
self.pageContent()
#页内函数
def pageContent(self):
#显示标签表单
self.addLineBtn = tkinter.Button(self.windows,width=70, height=1, text="增加一条新数据", bg="#F0F0F0",
command=self.runAdd)
self.addLineBtn.grid(row=5)
self.logs = tkinter.Text(self.windows, width=70, height=30, fg="black", bg="white")
self.logs.grid(row=7, column=0)
# 执行
def runAdd(self):
now_time = time.localtime(time.time())
self.logs.insert('1.0', '这是一条数据 日期:'+time.strftime('%Y-%m-%d %H:%M:%S',now_time)+'\n')
def start_home():
windows = tkinter.Tk()
homePage(windows)
windows.mainloop()
start_home()