- 环境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的现实内容text
theLabel=tk.Label(app,text="我的第二个窗口程序!")
theLabel.pack()
app.mainloop()
实例3
运用tkinter中的Label及Entry创建输入框获取作品及作者信息的界面
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)
#输入内容获取函数print打印
def show():
print("作品:《%s》"%e1.get())
print("作者:%s"%e2.get())
#清除函数,清除输入框的内容
def dele():
e1.delete(0,END)
e2.delete(0,END)
#设置两个按钮,点击按钮执行命令 command= 命令函数
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'表示当焦点移走时,就会调用validatecommand指定的函数
#invalidcommand出现错误时被调用指定函数
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的内容的
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里冲突不能执行
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()