- 環(huán)境python3.x 3.x之后tkinter自帶晦嵌,jupyter notebook
第一個小例子
from tkinter import *
root =Tk()
e =Entry(root) #輸入框賦值在e變量
e.pack(padx =20,pady =20) #輸入框的位置設定
e.delete(0,END) #把輸入框清空
e.insert(0,"默認文本...") #插入序號為0,后為字符串
mainloop()
第二個小例子
import tkinter as tk
#設置tkinter窗口
app=tk.Tk()
#設置窗口標題
app.title("Donkey Jason")
#設置Label的現(xiàn)實內(nèi)容text
theLabel=tk.Label(app,text="我的第二個窗口程序罩锐!")
theLabel.pack()
app.mainloop()
實例3
運用tkinter中的Label及Entry創(chuàng)建輸入框獲取作品及作者信息的界面
from tkinter import *
#設置tkinter窗口
root = Tk()
#繪制兩個label,grid()確定行列
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)
e2.grid(row =1 ,column =1)
#輸入內(nèi)容獲取函數(shù)print打印
def show():
print("作品:《%s》"%e1.get())
print("作者:%s"%e2.get())
#清除函數(shù),清除輸入框的內(nèi)容
def dele():
e1.delete(0,END)
e2.delete(0,END)
#設置兩個按鈕逗嫡,點擊按鈕執(zhí)行命令 command= 命令函數(shù)
theButton1 = Button(root, text ="獲取信息", width =10,command =show)
theButton2 = Button(root, text ="清除",width =10,command =dele)
#設置按鈕的位置行列及大小
theButton1.grid(row =3 ,column =0,sticky =W, padx=10,pady =5)
theButton2.grid(row =3 ,column =1,sticky =E, padx=10,pady =5)
mainloop()
例子4--validate作用
from tkinter import *
root = Tk()
root.title("validate")
label1=Label(root,text="請輸入正確用戶名:")
def test2():
if e1.get()=="Donkey Jason":
print("正確朵耕!")
return True
else:
print("錯誤!")
e1.delete(0,END)
return False
def test3():
print("提示:驢子")
return True
v = StringVar()
#validate ='focusout'表示當焦點移走時洞辣,就會調(diào)用validatecommand指定的函數(shù)
#invalidcommand出現(xiàn)錯誤時被調(diào)用指定函數(shù)
e1 =Entry(root,textvariable =v ,validate ='focusout',\
validatecommand =test2,invalidcommand =test3)
e2 =Entry(root)
label1.pack(padx=10,pady=10)
e1.pack(padx =10,pady =10)
e2.pack(padx =10,pady =10)
mainloop()
實例5
--密碼輸入
from tkinter import *
app = Tk()
Label(app, text= "賬號:").grid(row = 0, column = 0)
Label(app, text= "密碼:").grid(row = 1, column = 0)
#tkinter里的string變量用來存儲Entry里的textvariable
v1 = StringVar()
v2 = StringVar()
e1 = Entry(app, textvariable = v1)
e2 = Entry(app, textvariable = v2, show = "*")#show里可以是別的符號
e1.grid(row = 0, column = 1)
e2.grid(row = 1, column = 1)
def show():
print("賬號:%s"%e1.get())#get是用來獲取e1的內(nèi)容的
print("密碼:%s"%e2.get())
def dele():
e1.delete(0,END)
e2.delete(0,END)
theButton1 = Button(app, text = "確認",width = 10,command = show)
theButton2 = Button(app, text = "退出",width = 10,command = app.quit)#app.quit是退出IDLE里沖突不能執(zhí)行
theButton1.grid(row =3 ,column =0,sticky =W, padx=10,pady =5)
theButton2.grid(row =3 ,column =1,sticky =E, padx=10,pady =5)
mainloop()