【莫煩Python】Tkinter 做簡(jiǎn)單的窗口視窗 Python GUI


tkinter窗口
import tkinter as tk
window=tk.Tk()
window.title('my window')
window.geometry('200x100')
var=tk.StringVar()#變量用來代替顯示的字符串
#修改text=。。為textvariable=var,l代替label
#在window上面的label
l=tk.Label(window,textvariable=var,
#text='MOG!this is TK!',被上一行更換
bg='green',width=15,
height=2,#label的長(zhǎng)和高,以字符為單位
font=('Arial',12)#字體類型和大小
l.pack())
on_hit=False
def hit_me():
global on_hit
if on_hit==False:
on_hit=Ture
var.set('you hit me')
else:
on_hit=False
var.set('')
b=tk.Button(window,text='hit me',width=15,
height=2,command=hit_me)#按鈕,執(zhí)行功能或者函數(shù)方程,此處執(zhí)行函數(shù)hit_me
b.pack()
window.mainloop()#循環(huán),更新相當(dāng)與一個(gè)大的while循環(huán)
#畫布
import tkinter as tk
window=tk.Tk()
window.title('my window')
window.geometry('200*200')
canvas=tk.Canvas(window,bg='blue',height=100,width=200)
image_file=tk.PhotoImage(file='ins.gif')
image=canvas.create_image(0,0,anchor='nw',image=image_file)#鉚釘?shù)狞c(diǎn)(0,0)東北角
canvas.pack()
oval=canvas.create_oval(x0,y0,x1,y1,fill='red')#定義圓形
arc=canvas.create_arc(x0+30,y0+30,x1+30,y1+30,start=0,extent=180)
#定義扇形
rect=canvas.create_rectangle(100,30,100+20,30+20)
canvas.pack()
def moveit():
canvas.move(rect,0,2)
b.tk.Button(window,text='move',command=moveit)
window.mainloop()
#二節(jié)
import tkinter as tk
window=tk.Tk()
window.title('my window')
window.geometry('200*200')
e=tk.Entry(window,show='*'#show=None)
e.pack()
def insert_point():
var=e.get()
t.insert('insert',var)
def insert_end():
var=e.get()
t.insert('end',var)#t.insert(2.2,var)第二行的第二位
b1=tk.Button(window,text='hit me',width=15,
heighet=2,command=insert_point)
b1.pack()
b2=tk.Button(window,text='hit me',width=15,
heighet=2,command=insert_point)
b2.pack()
t=tk.Text(window,height=2)
t.pack()
#列表控位
#畫布
import tkinter as tk
window=tk.Tk()
window.title('my window')
window.geometry('200*200)
canvas=tk.Canvas(window,bg='blue',height=100,width=200)
image_file=tk.PhotoImage(file='ins.gif')
image=canvas.create_image(0,0,anchor='nw',image=image_file)#最中間那個(gè)點(diǎn)鉚釘在10,10
x0,y0,x1,y1=50,50,80,80
line=canvas.create_line(x0,y0,x1,y1)
oval=canvas.create_oval(x0,y0,x1,y1,fill='red')
arc=canvas.create_arc(x0+30,y0+30,y1+30,
x1+30,start=0,extent=180)
rect=canvas.create_rectangle(100,30,100+20,30+20)
canvas.pack()
def moveit():
canvas.move(rect,0,2)
b=tk.Button(window,text='move',command=moveit).pack()
window.mainloop()
canvas.pack()
canvas.pack()
#放置部件
pack方式
window.title('my window')
window.geometry('200*200')
tk.Label(window,text=1).pack(side='top')
tk.Lbel(window,text=1).pack(side='bottom')
tk.Label(window,text=1).pack(side='left')
tk.Label(window,text=1).pack(side='right')
window.mainloop()
grid#格子
window.title('my window')
window.geometry('200*200')
for i in range(4):
for j in range(3):
tk.Label(window,text=1).grid(row=i,column=j,
ipadx=10,ipady=10)#方向擴(kuò)展i內(nèi)部擴(kuò)展
window.mainloop()
#另一種方式place
window.title('my window')
window.geometry('200*200')
tk.Label(window,text=1).place(x=10,y=100,
anchor='nw')