tkinter學習(4)frame、pack、canvas學習


1.frame和pack學習

1.1 代碼:

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('600x400+500+0')

#tk.Label(window, text='on the window').pack() #這種寫法很簡潔
#與下面這種寫法等同,注意pack的位置
l=tk.Label(window, text='on the window')
l.pack()

frm = tk.Frame(window) #定義一個frame=frm,在Window上
frm.pack()

frm_l = tk.Frame(frm) #在frm上定義frm2個框架
frm_r = tk.Frame(frm)
frm_l.pack(side='left') #pack位置,side=left和right,當然還有top和bottom
frm_r.pack(side='right')

tk.Label(frm_l, text='on the frm_l1').pack()
tk.Label(frm_r, text='on the frm_r1').pack()
#這種布局是依次的,看懂了么?
tk.Label(frm_l, text='on the frm_l2').pack()
tk.Label(frm_l, text='on the frm_l3').pack()
tk.Label(frm_l, text='on the frm_l4').pack()
tk.Label(frm_l, text='on the frm_l5').pack()

window.mainloop()
View Code

 

1.2 圖1

2.canvas畫布的學習

2.1 代碼:

import tkinter as tk
#初始定義窗口,標題,大小和位置
window = tk.Tk()
window.title('my window')
window.geometry('800x500+500+0')
#定義畫布canvas(是位於Window的一個畫布)、大小和背景顏色,pack布局方法2種,但這里只能這種
canvas = tk.Canvas(window, bg='pink', height=300, width=300)
canvas.pack() 
#canvas = tk.Canvas(window, bg='pink', height=300, width=300).pack() #這種布局就會報錯
#因為以下的功能屬性比如create_image是canvas的屬性
#---------以下這些是canvas的內容
#定義導入圖片設置
image_file = tk.PhotoImage(file='ins.gif') #圖片ins.gif這種代表系統的默認位置本機位置是:/home/xgj
#0,0,是指坐標x=0,y=0,就是左上角頂點處
# anchor就是錨定位置為nw(必須是小寫)=西北角,當然也可以是center等等
image = canvas.create_image(0, 0, anchor='nw', image=image_file)
#初始賦值
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') #畫圓
#注意參數start從0°(水平向右的為0°)開始,到extent120°(往左畫扇形,120°就會更直觀)結束
arc = canvas.create_arc(x0+80, y0+80, x1+80, y1+80, start=0, extent=120) #畫扇形
rect = canvas.create_rectangle(100, 30, 100+20, 30+20) #畫長方形

#-------以上是canvas的內容
#canvas.pack() ,也可以放在這個位置

#定義函數
def moveit():
canvas.move(rect, 0, 2) 
#move的對象是rect這個正方形,x=0,y=2,就是x坐標不變,y坐標每次向下移動2個像素

b = tk.Button(window, text='move', command=moveit).pack() #這種pack沒有關系

window.mainloop()
View Code

 

2.2 圖2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM