1 概述
1. 方法:使用 lambda
(1) lambda: func1(1, 2)
(2) lambda: [func1(1, 2), func2(a, b)]
2. 说明
(1) 函数必须带 '()', 无论是否有参数
(2) 调用多个函数时,'[]' 不能省略
2 实例
2.1 无参数
import tkinter
def func():
print("Click !")
def main():
window = tkinter.Tk()
window.title('无参数')
window.geometry('300x100+500+300')
btn = tkinter.Button(text='按钮', width=10, height=3, command=func)
btn.pack(pady=10)
window.mainloop()
if __name__ == '__main__':
main()
2.2 有参数
import tkinter
def func(x, y):
print(f'x = {x}, y = {y}')
def main():
window = tkinter.Tk()
window.title('有参数')
window.geometry('300x100+500+300')
btn = tkinter.Button(text='按钮', width=10, height=3,
command=lambda: func(1, 2))
btn.pack(pady=10)
window.mainloop()
if __name__ == '__main__':
main()
2.3 多个函数
import tkinter
def func1(a):
print(f'Say: a = {a}')
def func2(a, b):
print(f'Say: a = {a}, b = {b}')
def main():
window = tkinter.Tk()
window.title('无参数')
window.geometry('300x100+500+300')
btn = tkinter.Button(text='按钮', width=10, height=3,
command=lambda: [func1(1), func2(1, 2)])
btn.pack(pady=10)
window.mainloop()
if __name__ == '__main__':
main()
3 实战
from tkinter import *
import logging
class Window:
def __init__(self):
self.window = Tk()
self.window.title('演示写入数据')
screenwidth = self.window.winfo_screenwidth()
screenheight = self.window.winfo_screenheight()
size = self.window_of_center(screenwidth, screenheight)
self.window.geometry(size)
self.window.resizable(0, 0)
self.message = StringVar()
self.layout()
self.window.mainloop()
@staticmethod
def window_of_center(screenwidth, screenheight, width=400, height=200):
"""
设置窗口居中
:param screenwidth: 屏幕宽
:param screenheight: 屏幕高
:param width: 窗体宽
:param height: 窗体高
:return: 窗体大小及位置 size
"""
size = '%dx%d+%d+%d' % (width,
height,
(screenwidth - width) / 2,
(screenheight - height) / 2)
logging.info(f'屏幕(宽 x 高): {screenwidth} x {screenheight}')
logging.info(f'窗口(宽 x 高): {width} x {height}')
return size
def layout(self):
"""
页面布局
:return:
"""
hint = Label(self.window, text='请输入:', fg='blue', font=('宋体', 10), anchor='e')
entry = Entry(self.window, bd=1, textvariable=self.message)
btn = Button(self.window, text='确定', command=lambda: self.show_text(text))
text = Text(self.window, width=45, height=10)
hint.place(x=5, y=10, width=80, height=20)
entry.place(x=95, y=10, width=200, height=20)
btn.place(x=300, y=10, height=20)
text.place(x=40, y=50)
def show_text(self, text):
"""
插入文本内容,带参数
:param text: 文本框
:return:
"""
text.insert(INSERT, self.message.get())
logging.info(f'写入 message = {self.message.get()}')
self.message.set('')
logging.info('清空 message 成功')
if __name__ == '__main__':
logger = logging.getLogger()
logger.setLevel(logging.INFO)
Window()