1、Tkinter模塊的基本使用php
1)實例化窗口程序html
import tkinter as tk app = tk.Tk() app.title("FishC Demo") app.mainloop()
2)窗口生成一個標題文本java
import tkinter as tk # 第一步實例化tk,用於容納整個程序 app = tk.Tk() app.title("FishC Demo") # 設置標題欄 # 第二步,用於顯示文本,或圖片 thelabel =tk.Label(app,text="個人第二個窗口程序") # Label 實例化標籤 thelabel.pack() # 用於自動調節組件的尺寸 # 窗口的組事件循環 app.mainloop()
3)用類來實現簡單的窗口python
import tkinter as tk class App: def __init__(self,master): frame = tk.Frame(master) frame.pack() self.hi_there = tk.Button(frame,text='打招呼',fg = 'blue') self.hi_there.pack() root = tk.Tk() app = App(root) root.mainloop()
4)類中,建立點擊方法,修改文本位置,及背景方法git
import tkinter as tk class App: def __init__(self,master): frame = tk.Frame(master) frame.pack(side = tk.LEFT,padx = 10,pady = 10) self.hi_there = tk.Button(frame,text='打招呼',bg = 'blue',fg = 'white',command=self.say_hi) self.hi_there.pack() def say_hi(self): print('歡迎來到GUI編程') root = tk.Tk() app = App(root) root.mainloop()
5)添加圖片功能web
from tkinter import * root = Tk() textlabel = Label(root,text='你勇敢嗎!') textlabel.pack(side = LEFT) photo = PhotoImage(file = "1.png") imgLabel = Label(root,image=photo) imgLabel.pack(side = RIGHT) mainloop()
6)對文字屬性編輯編程
from tkinter import * root = Tk() textlabel = Label(root,text='你勇敢嗎!,\n敢來嗎',justify=LEFT,padx=10) # justify=LEFT 左對齊 padx=10 邊距是10 textlabel.pack(side = LEFT) photo = PhotoImage(file = "1.png") imgLabel = Label(root,image=photo) imgLabel.pack(side = RIGHT) mainloop()
7)設置成背景圖片ruby
from tkinter import * root = Tk() photo = PhotoImage(file='1.jpg') theLabel = Label(root, text="the beautiful girl", justify= LEFT, image=photo, compound=CENTER, font=("宋體",25), fg="black") theLabel.pack() mainloop()
2、Button組件 app
1)Button點擊觸發事件ide
from tkinter import * def callback(): var.set("吹吧,我纔不信") pass root = Tk() frame1 = Frame(root) frame2 = Frame(root) var = StringVar() var.set("你勇敢嗎!,\n敢來嗎") textlabel = Label(frame1, textvariable=var, justify=LEFT, padx=10) # textvariable是變量字符串 justify=LEFT 左對齊 padx=10 邊距是10 textlabel.pack(side = LEFT) photo = PhotoImage(file = "1.png") imgLabel = Label(frame1,image=photo) imgLabel.pack(side = RIGHT) theButton = Button(frame2,text="肯定,你就點啊",command = callback) theButton.pack() frame1.pack(padx=10,pady=10) frame2.pack(padx=10,pady=10) mainloop()
2)記錄Button的點擊記錄事件
from tkinter import * root = Tk() v = IntVar() c = Checkbutton(root,text="測試一下",variable=v) # variable=v 表示按鈕狀態是否被按下 c.pack() l = Label(root,textvariable=v) # 記錄選中狀態 l.pack() mainloop()
3)Button點擊事件列表應用
from tkinter import * root = Tk() GIRLS = ["西施","蒼老師",'東施'] v = [] for girl in GIRLS: v.append(IntVar()) b = Checkbutton(root,text=girl,variable=v[-1]) b.pack(anchor=W) # 名字左對齊 mainloop()
4)互斥事件
from tkinter import * root = Tk() v = IntVar() Radiobutton(root,text='One',variable=v,value=1).pack(anchor=W) Radiobutton(root,text='Two',variable=v,value=2).pack(anchor=W) Radiobutton(root,text='Threr',variable=v,value=3).pack(anchor=W) mainloop()
5)for循環使用互斥事件和按鈕的多樣式
from tkinter import * root = Tk() LANGS=[("python",1), ("java",2), ("php",3), ("ruby",4)] v = IntVar() v.set(1) for lang,num in LANGS: b = Radiobutton(root,text=lang,variable=v,value=num,indicatoron=False) # indicatoron=False 設置點擊的樣式,默認的小原點 b.pack(fill=X) # 按鈕橫向填充 mainloop()
6)選擇回答選項設置
from tkinter import * root = Tk() group = LabelFrame(root,text="最好的腳本語言是?",padx=5,pady=5) group.pack(padx=10,pady=10) LANGS=[("python",1), ("java",2), ("php",3), ("ruby",4)] v = IntVar() # v.set(1) # 這個是默認選擇第一個 for lang,num in LANGS: b = Radiobutton(group,text=lang,variable=v,value=num) # indicatoron=False 設置點擊的樣式,默認的小原點 b.pack(anchor=W) mainloop()
3、Entry輸入框方法
1)初探輸入框
from tkinter import * root = Tk() e = Entry(root) e.pack(padx=20,pady=20) mainloop()
2)生成默認輸入框文本
from tkinter import * root = Tk() e = Entry(root) e.pack(padx=20,pady=20) e.delete(0,END) e.insert(0,"默認文本...") mainloop()
3)獲取用戶交互點擊信息
from tkinter import * root = Tk() Label(root,text="做品:").grid(row=0,column=0) Label(root,text="做者:").grid(row=1,column=0) e1 = Entry(root) e2 = Entry(root) e1.grid(row=0,column=1,padx=10,pady=5) e2.grid(row=1,column=1,padx=10,pady=5) def show(): print("做品:<%s>" % e1.get()) print("做者:<%s>" % e2.get()) Button(root,text="獲取信息",width=10,command=show)\ .grid(row=3,column=0,sticky=W,padx=10,pady=5) Button(root,text="退出",width=10,command=root.quit) \ .grid(row=3, column=1, sticky=E, padx=10, pady=5) mainloop()
4)輸入框隱藏輸入密碼功能
from tkinter import * root = Tk() Label(root,text="帳號:").grid(row=0,column=0) Label(root,text="密碼:").grid(row=1,column=0) v1 = StringVar() v2 = StringVar() e1 = Entry(root,textvariable=v1) e2 = Entry(root,textvariable=v2,show="*") e1.grid(row=0,column=1,padx=10,pady=5) e2.grid(row=1,column=1,padx=10,pady=5) def show(): print("帳號:%s" % e1.get()) print("密碼:%s" % e2.get()) Button(root,text="芝麻開門",width=10,command=show)\ .grid(row=3,column=0,sticky=W,padx=10,pady=5) Button(root,text="退出",width=10,command=root.quit) \ .grid(row=3, column=1, sticky=E, padx=10, pady=5) mainloop()
5)輸入框正確則保留,錯誤清空從新輸入
from tkinter import * master = Tk() def test(): if e1.get() == "python": print("正確") return True else: print("錯誤") e1.delete(0,END) return False v = StringVar() e1 = Entry(master,textvariable=v,validate="focusout",validatecommand=test) e2 = Entry(master) e1.pack(padx = 10,pady=10) e2.pack(padx = 10,pady=10) mainloop()
6)函數調用使用
#-*-coding: utf-8 -*- from tkinter import * master = Tk() def test1(): if e1.get() == "python": print("正確") return True else: print("錯誤") e1.delete(0,END) return False def test2(): print("python被調用了") return True v = StringVar() e1 = Entry(master,textvariable=v,validate="focusout",\ validatecommand=test1,invalidcommand=test2) e2 = Entry(master) e1.pack(padx = 10,pady=10) e2.pack(padx = 10,pady=10) mainloop()
7)驗證函數的額外選項
from tkinter import * master = Tk() v = StringVar() def test(content,reason,name): if content == "python": print("正確") print(content,reason,name) return True else: print("錯誤") print(content, reason, name) return False testCMD = master.register(test) e1 = Entry(master,textvariable=v,validate="focusout",\ validatecommand=(testCMD,'%P','%v','%W')) e2 = Entry(master) e1.pack(padx = 10,pady=10) e2.pack(padx = 10,pady=10) mainloop()
8)實現一個簡單的加法計算器
from tkinter import * master = Tk() frame = Frame(master) frame.pack(padx=10,pady=10) v1 = StringVar() v2 = StringVar() v3 = StringVar() def test(content): return content.isdigit() testCMD = master.register(test) e1 = Entry(frame,width=10,textvariable=v1,validate="key",\ validatecommand=(testCMD,'%P')).grid(row=0,column=0) Label(frame,text="+").grid(row=0,column=1) e2 = Entry(frame,width=10,textvariable=v2,validate="key",\ validatecommand=(testCMD,'%P')).grid(row=0,column=2) Label(frame,text="=").grid(row=0,column=3) e3 = Entry(frame,width=10,textvariable=v3,state="readonly").grid(row=0,column=4) def calc(): result = int(v1.get()) + int(v2.get()) v3.set(str(result)) Button(frame,text='計算結果',command=calc).grid(row=1,column=2,pady=5) mainloop()
9)Listbox組件使用,引出滾動條
實現單一的刪除操做
from tkinter import * master = Tk() theLB = Listbox(master) theLB.pack() for item in ['雞蛋','鴨蛋','鵝蛋','狗蛋']: theLB.insert(END,item) theButton = Button(master, text="刪除它",\ command = lambda x=theLB:x.delete(ACTIVE)) theButton.pack() # theLB.delete(0,END) # 所有刪除 mainloop()
theLB = Listbox(master,selectmode=EXTENDED) # 多選 theLB = Listbox(master,selectmode=SINGLE) # 單選 theLB = Listbox(master,selectmode=SINGLE,height=15) # 增長高度
4、滾動條操做
1)Scrikkbar生成滾動條方法
from tkinter import * root = Tk() sb = Scrollbar(root) sb.pack(side=RIGHT,fill =Y) mainloop()
2)另外一種 Scale增長精度的滾動條
from tkinter import * root = Tk() Scale(root,from_=0, to =42).pack() Scale(root,from_=0, to =200,orient = HORIZONTAL).pack() mainloop()
3)獲取該精度的位置
from tkinter import * root = Tk() s1 = Scale(root,from_=0, to =42) s1.pack() s2 = Scale(root,from_=0, to =200,orient = HORIZONTAL) s2.pack() def show(): print(s1.get(),s2.get()) Button(root,text="獲取位置",command =show).pack() mainloop()
4)精度的具體演示
from tkinter import * root = Tk() s1 = Scale(root,from_=0, to =42,tickinterval=5,resolution=5,length=200) s1.pack() s2 = Scale(root,from_=0, to =200,tickinterval=10,orient = HORIZONTAL,length=600) s2.pack() mainloop()
5、insert插入功能
1)插入文本
from tkinter import * root = Tk() text = Text(root, width=30, height=5) text.pack() text.insert(INSERT,"I love \n") text.insert(END,"YOU") def show(): print("我被點了一下") b1 = Button(text,text="點我啊",command=show) text.window_create(INSERT,window=b1)
2)插入圖片
from tkinter import * root = Tk() text = Text(root, width=30, height=30) text.pack() phone = PhotoImage(file = "1.jpg") def show(): text.image_create(END,image=phone) b1 = Button(text,text="點我啊",command=show) text.window_create(INSERT,window=b1) mainloop()
3)指定位置改變字體顏色
from tkinter import * root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") text.tag_add("tag1","1.7","1.12","1.14") text.tag_config("tag1",background="yellow",foreground="red") mainloop()
4)顏色覆蓋,後者覆蓋前者
from tkinter import * root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") text.tag_add("tag1","1.7","1.12","1.14") text.tag_add("tag2","1.1","1.9","1.14") text.tag_config("tag1",background="yellow",foreground="red") text.tag_config("tag2",foreground="blue") mainloop()
5)綁定事件,超連接
from tkinter import * import webbrowser root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") text.tag_add("link","1.7","1.16") text.tag_config("link",foreground="blue",underline=True) def show_arrow_cursor(event): text.config(cursor="arrow") def show_xterm_curror(event): text.config(cursor="xterm") def click(event): webbrowser.open("http://www.baidu.com") text.tag_bind("link","<Enter>",show_arrow_cursor) text.tag_bind("link","<Leave>",show_xterm_curror) text.tag_bind("link","<Button-1>",click) mainloop()
6)檢查文本是否發生了變更
from tkinter import * import hashlib root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") contents = text.get("1.0",END) def getSig(contents): m = hashlib.md5(contents.encode()) return m.digest() sig = getSig(contents) def check(): contents = text.get("1.0", END) if sig != getSig(contents): print("警報:內容發生變更") else: print("風平浪靜") Button(root,text="檢查",command=check).pack() mainloop()
7)對文本進行全局收索
from tkinter import * import hashlib root = Tk() text = Text(root,width=30,height=5) text.pack() text.insert(INSERT,"I love FishC.com!") def getIndex(start,index): return tuple(map(int,str.split(text.index(index),"."))) start = "1.0" while True: pos = text.search("o",start,stopindex=END) if not pos: break print("找到啦,位置是:",getIndex(text,pos)) start = pos + "+1c" mainloop()
8)撤銷操做,自動插入分隔符
from tkinter import * root = Tk() text = Text(root,width=30,height=5,undo=True) text.pack() text.insert(INSERT,"I love FishC.com!") def show(): text.edit_undo() Button(root,text="撤銷",command=show).pack() mainloop()
9)撤銷,一個字符一個字符的刪除
from tkinter import * root = Tk() text = Text(root,width=30,height=5,undo=True,autoseparators=False) # autoseparators 去銷自動插入分隔符 text.pack() text.insert(INSERT,"I love FishC.com!") def callback(event): # 綁定事件須要加參數 text.edit_separator() # 人爲的插入分割符 text.bind('<Key>',callback) def show(): text.edit_undo() Button(root,text="撤銷",command=show).pack() mainloop()
原文連接:http://bbs.fishc.com/thread-59443-1-1.html