tkinter模块(tkinter是一个跨平台的PythonGUI工具包):
#Tkinter是一个跨平台的Python GUI工具包 import tkinter top=tkinter.Tk() #可以不写 btn=tkinter.Button() #pack()控制从属控件在所属主体内部出现的位置 btn.pack() btn["text"]="Click Me!" def clicked(): print("I was clicked!") btn["command"]=clicked #不能是clicked(),要指向函数本身。 #下面的写法也可以 #btn.config(text="Click Again",command=clicked) #如果没有指定主控件,则指向顶级主窗口 tkinter.Button(text="Click Again",command=clicked).pack() tkinter.Label(text="I'm in the first window!").pack() #建立主窗口外另一个窗口,并用label指向它 second=tkinter.Toplevel() tkinter.Label(second,text="I'm in the second window!").pack() for i in range(10): tkinter.Button(text=i).pack() def callback(event): print(event.x,event.y) #通过bind关联事件到top top.bind("<Button-1>",callback) tkinter.mainloop() print("Finish")
GUI文本编辑器:
#Tkinter是一个跨平台的Python GUI工具包 import tkinter,tkinter.scrolledtext #---------------------------------------- Top=tkinter.Tk() Top.title("simple editor") TextContents=tkinter.scrolledtext.ScrolledText() #pack()控制从属控件在所属主体内部出现的位置 TextContents.pack(side=tkinter.BOTTOM,expand=True,fill=tkinter.BOTH) FileName=tkinter.Entry() FileName.pack(side=tkinter.LEFT,expand=True,fill=tkinter.X) #---------------------------------------- def load(filename,contents): with open(filename.get()) as file: contents.delete("1.0",tkinter.END) contents.insert(tkinter.INSERT,file.read()) def save(filename,contents): with open(filename.get(),"w") as file: file.write(contents.get("1.0",tkinter.END)) #----------------------------------------- def buttonLoad(): load(FileName,TextContents) def buttonSave(): save(FileName,TextContents) tkinter.Button(text="Open",command=buttonLoad).pack(side=tkinter.LEFT) tkinter.Button(text="Save",command=buttonSave).pack(side=tkinter.LEFT) #----------------------------------------- tkinter.mainloop()
from tkinter import * from tkinter.scrolledtext import ScrolledText #--------------------- top=Tk() top.title("simple editor") contents=ScrolledText() #pack()控制从属控件在所属主体内部出现的位置 contents.pack(side=BOTTOM,expand=True,fill=BOTH) filename=Entry() filename.pack(side=LEFT,expand=True,fill=X) #---------------------- def load(): with open(filename.get()) as file: contents.delete("1.0",END) contents.insert(INSERT,file.read()) def save(): with open(filename.get(),"w") as file: file.write(contents.get("1.0",END)) #---------------------- Button(text="Open",command=load).pack(side=LEFT) Button(text="Save",command=save).pack(side=LEFT) mainloop()