使用tkinter编写简单程序
tkinter_demo.py
from tkinter import * from tkinter.scrolledtext import ScrolledText from button_def import Btn_def top = Tk() top.title("TEXT EDITOR") contents = ScrolledText() contents.pack(side=BOTTOM, expand=True, fill=BOTH) filename = Entry() filename.pack(side=LEFT, expand=True, fill=X) Btn = Btn_def() btn1 = Button(top, text='open', command=lambda: Btn.load(filename.get(), contents)).pack(side=RIGHT) btn2 = Button(top, text='save', command=lambda: Btn.save(filename.get(), contents)).pack(side=RIGHT) top.mainloop()
知识要点:
一、pack()
参数side:指定将控件停靠在哪一条边上,LEFT、RIGHT、TOP或BOTTOM
参数expand:让控件随父控件(这里是窗口)一起增大,可将expand设为True
二、ScrolledText控件
编辑区域
三、Entry控件
要提取Entry控件的内容,可以使用get方法
四、Button控件
参数text:设置控件的名字
参数command:控件的事件处理,注意,command传递参数是使用lambda:,否则控件自动执行
button_def.py
知识要点:
注意:contents为ScrolledText()对象的实例
contents:
调用方法delete和insert时,需要使用合适的参数来指定文本的位置。
在这里,我们使用'1.0'来指定第1行第0个字符(即第一个字符前面),使用END来指定文本的末尾,并使用INSERT来指定当前的插入点。
运行结果:
文章来源: Tkinter 实现简易文本编辑器