要初始化一个根窗口
最最基本格式:
from tkinter import *
root = tk.Tk()
root.mainloop()
最基本封装:
import tkinter as tk
class APP:
def __init__(self,master):
frame = tk.Frame(master)
frame.pack() #必须,调节窗体位置
self.bt = tk.Button(frame,text="点击这里",fg="前景色",bg="背景色",command=self.事件函数)
self.bt.pack()
def 事件函数(self):
print('aa')
root = tk.Tk()
app = APP(root)
root.mainloop()
组件的散落:
from tkinter import *
root = Tk()
textLabel = Label(root,text="以下内容\n只有18岁以上可以访问",
justify=LEFT,
padx=10)
textLabel.pack(side=LEFT)
photo = PhotoImage(file="1.gif")
imgLabel = Label(root,image=photo)
imgLabel.pack(side=RIGHT)
mainloop()
组件的散落:
Label(masterNone,**options)
Label(master,text="",anchor=八个方位,justify=文字对齐位置LEFT,RIGHT)
p = PhotoImage(file="图片路径")
Label(master,image=p)
Button(master,text="",command=callback)
b = Checkbutton(master, image=bold, variable=var, indicatoron=0)
Checkbutton(master,text="",variable=var)
var = StringVar()
var.set("T")
c = Checkbutton(master, text="你有女朋友吗?", variable=var, onvalue="T", offvalue="F")
def __init__(self, master):
self.var = IntVar()
c = Checkbutton(master, text="DUANG~", variable=self.var, command=self.cb)
c.pack()
单选:Radiobutton,主要是分组
from tkinter import *
master = Tk()
GIRLS = [
("西施", 1),
("王昭君", 2),
("貂蝉", 3),
("杨玉环", 4)]
v = IntVar()
for girl, num in GIRLS:
b = Radiobutton(master, text=girl, variable=v, value=num)
b.pack(anchor=W)
mainloop()
def cb(self, event):
print "variable is", self.var.get()
Frame:
from tkinter import *
Label(text="天王盖地虎").pack()
separator = Frame(height=2, bd=1, relief=SUNKEN)
separator.pack(fill=X, padx=5, pady=5)
Label(text="小鸡炖蘑菇").pack()
mainloop()
LabelFrame分组:
from tkinter import *
master = Tk()
group = LabelFrame(master, text="你从哪里得知鱼C?", padx=5, pady=5)
group.pack(padx=10, pady=10)
v = IntVar()
r1 = Radiobutton(group, text="同学/同事介绍", variable=v, value=1).pack(anchor=W)
r2 = Radiobutton(group, text="老婆大人介绍", variable=v, value=2).pack(anchor=W)
r3 = Radiobutton(group, text="老师/学长介绍", variable=v, value=3).pack(anchor=W)
mainloop()
文本输入框:entry
from tkinter import *
master = Tk()
e = Entry(master)
e.pack(padx=20, pady=20)
e.delete(0, END)
e.insert(0, "默认文本...")
mainloop()
文本框验证:
设置validate、validatecommand和invalidcommand选项
Entry(master,textvariable=v,validate="验证类型",validatecommand=事件1,invalidcommand=失败事件)
额外参数:
from tkinter import *
master = Tk()
v = StringVar()
def test(content, reason, name):
if content == "小甲鱼":
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()