Text組件:比較複雜
from tkinter import *
root =Tk()
#30字符寬,2行高度
text = Text(root, width=30, height=2)
text.pack()
text.insert(INSERT, 'I love \n')
text.insert(END,'lol')
photo = '圖片路徑'
def show():
print('hahah ,dianwo le ')
#插入圖片
text.image_create(END, image = photo)
b1 = Button(root,text='點我點我',command=show)
b1.pack()
mainloop
indexes 索引
canvas畫布
from tkinter import*
root = Tk()
w = Canvas(root, width=400, height =250)
w.pack()
#event鼠標點擊的點
def paint(event):
x1,y1 = (event.x - 1),(event.y - 1)
x2,y2 = (event.x + 1),(event.y + 1)
w.create_oval(x1,y1,x2,y2, fill = 'red')
#綁定鼠標左鍵
w.bind('<B1-Motion>',paint)
Label(root,text='start your painting..').pack(side=BOTTOM)
mainloop()
編程上畫橢圓 ,正方形: 矩形,
w = canvas(root,width=400,height=200)
w.pack()
w.create_rectangle(40,20,160,20, fill=‘yellow’)
其他兩個類似 ,設置座標即可。
Menu菜單
from tkinter import*
root = Tk()
def callback():
print('你好')
menubar = Menu(root)
menubar.add_command(label ='hello', command = callback)
menubar.add_command(label ='quit', command = root.quit)
#將menu和 menubar關聯起來
root.config(menu=menubar)
mainloop()
from tkinter import*
root = Tk()
def callback():
print('你好')
#filemenu 來自於menubar 屬於menubar的filemenu
menubar = Menu(root)
#tearoff 設置爲不能撕開,即 不能放大
filemenu = Menu(menubar, tearoff=False)
filemenu.add_command(label ='hello', command = callback)
filemenu.add_command(label ='quit', command = callback)
#設置分割
filemenu.add_separator()
filemenu.add_command(label ='退出', command = root.quit)
#創建級聯菜單 ,
menubar.add_cascade(label='文件',menu =filemenu)
#filemenu 來自於menubar 屬於menubar的filemenu
editmenu= Menu(menubar,tearoff=False)
editmenu.add_command(label ='copy', command = callback)
editmenu.add_command(label ='paste', command = callback)
#設置分割
editmenu.add_separator()
editmenu.add_command(label ='edit', command = root.quit)
#創建級聯菜單 ,
menubar.add_cascade(label='quit' ,menu = editmenu)
#將menu和 menubar關聯起來
root.config(menu=menubar)
mainloop()
popup彈出窗口
from tkinter import *
root = Tk()
def callback():
print('你好')
#filemenu 來自於menubar 屬於menubar的filemenu
menubar = Menu(root)
menubar.add_command(label ='hello', command = callback)
menubar.add_command(label ='quit', command = callback)
#設置分割
frame =Frame(root, width=512, height=512)
frame.pack()
#event.x event.y 是相對於屏幕的位置
#event.x_root event.y_root相對於應用程序的位置
def popup(event):
menubar.post(event.x_root, event.y_root)
#綁定鼠標右鍵 觸發
#<key>鍵盤事件
#<Motion>綁定移動時間
frame.bind('<Button-3>',popup)
mainloop()