一个平民 发表于 2023-5-27 21:25:57

Python丨tkinter开发常用的29种功能用法(建议码住)

在Python软件开发中,tkinter中command功能的作用是为按钮、菜单等组件绑定回调函数,用户操作该组件时会触发相应的函数执行。
本文涵盖了各种组件和功能:
1、为Button组件(按钮)绑定回调函数
import tkinter as tk
def say_hello():
    print("Hello World!")root = tk.Tk()
button = tk.Button(root, text="点我", command=say_hello)
button.pack()
root.mainloop()
 
https://img-blog.csdnimg.cn/39dd127be63d43e990c05db1cbfb24e5.png
2、为Checkbutton组件(多选择钮)绑定回调函数
import tkinter as tkdef show_selection():
    print("Selection is:", var.get())root = tk.Tk()var = tk.BooleanVar()checkbutton = tk.Checkbutton(root, text="Select me", variable=var, command=show_selection)
checkbutton.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/de435db1e4cb4ba394e7bb51852fd66d.png
3、为Radiobutton组件(单选择钮)绑定回调函数
import tkinter as tkdef show_selection():
    print("Selection is:", var.get())root = tk.Tk()var = tk.StringVar()radiobutton1 = tk.Radiobutton(root, text="Option 1", variable=var, value="Option 1", command=show_selection)
radiobutton2 = tk.Radiobutton(root, text="Option 2", variable=var, value="Option 2", command=show_selection)radiobutton1.pack()
radiobutton2.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/08c693fc3e3a46d8b512dab4a651620b.png
4、为Listbox组件(列表组件)绑定回调函数
import tkinter as tkdef show_selection(event):
    selection = event.widget.curselection()
    print("Selection is:", event.widget.get(selection))root = tk.Tk()listbox = tk.Listbox(root)
listbox.insert("end", "Option 1")
listbox.insert("end", "Option 2")
listbox.bind("<<ListboxSelect>>", show_selection)listbox.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/4bdf11dfeed14cb9aa24f019f599f1cf.png
5、为Spinbox组件(条框)绑定回调函数
import tkinter as tk
# Python学习交流扣裙:708525271
def show_selection():
    print("Selection is:", spinbox.get())root = tk.Tk()spinbox = tk.Spinbox(root, values=(1, 2, 3,4,5), command=show_selection)
spinbox.pack()root.mainloop() 
运行后,选择不同的参数,回传到了spinbox组件

 
https://img-blog.csdnimg.cn/dfd5fa4ad9954aa9a644d64df149c1c8.png
6、为Scale组件(滑条)绑定回调函数
import tkinter as tkdef show_selection(value):
    print("Selection is:", value)root = tk.Tk()scale = tk.Scale(root, from_=0, to=100, command=show_selection)
scale.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/7a73217eea524d32aab04b564f1e85e3.png
7、为Scrollbar组件(滚动条)绑定回调函数
import tkinter as tkdef scroll(event):
    scrollbar.set(event.widget.get())root = tk.Tk()scrollbar = tk.Scrollbar(root, orient="vertical")
scrollbar.pack(side="right", fill="y")listbox = tk.Listbox(root, yscrollcommand=scrollbar.set)
for i in range(100):
    listbox.insert("end", "Option " + str(i))scrollbar.config(command=listbox.yview)
listbox.bind("<MouseWheel>", scroll)listbox.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/d735a51d6373412bacea69a066c0bfad.png
8、为Canvas组件(画布)绑定回调函数
import tkinter as tkdef draw_line(event):
    canvas.create_line(0, 0, event.x, event.y)root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
canvas.bind("<Button-1>", draw_line)canvas.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/3eed878ada644121917a0bc56f41f40e.png
9、为Text组件(文本框)绑定回调函数
import tkinter as tkdef count_characters(event):
    text = event.widget.get("1.0", "end")
    count = len(text.replace("\n", ""))
    print("Character count:", count)root = tk.Tk()text = tk.Text(root)
text.bind("<KeyRelease>", count_characters)text.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/e15e220978ef4813ba4c483aab2485e1.png
10、为Menu组件(菜单)绑定回调函数
import tkinter as tkdef say_hello():
    print("Hello World!")root = tk.Tk()menubar = tk.Menu(root)filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New")
filemenu.add_command(label="Open")
filemenu.add_command(label="Save")filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)editmenu = tk.Menu(menubar, tearoff=0)
editmenu.add_command(label="Copy")
editmenu.add_command(label="Cut")
editmenu.add_command(label="Paste")
editmenu.add_command(label="显示问候",command=say_hello)helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="About")menubar.add_cascade(label="File", menu=filemenu)
menubar.add_cascade(label="Edit", menu=editmenu)
menubar.add_cascade(label="Help", menu=helpmenu)root.config(menu=menubar)root.mainloop()
 
https://img-blog.csdnimg.cn/a8069e0037ad432d88d53571e33fadfa.png
11、为Canvas(画布)中的图形对象绑定回调函数
import tkinter as tkdef move_object(event):
    canvas.move(rectangle, 10, 10)root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
rectangle = canvas.create_rectangle(50, 50, 100, 100, fill="blue")
canvas.tag_bind(rectangle, "<Button-1>", move_object)canvas.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/4545b5da35d3444697d4c711000fb9a9.png
当点击蓝色方块时,蓝色方块会移动
12、为Frame组件绑定回调函数
import tkinter as tkdef say_hello():
    print("Hello World!")root = tk.Tk()frame = tk.Frame(root)
button = tk.Button(frame, text="Click me", command=say_hello)
button.pack()
frame.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/a1240c45a7a14e4e99a8d17519016c72.png
13、为Label组件(标签)绑定回调函数
import tkinter as tkdef say_hello(event):
    label.config(text="Hello World!")root = tk.Tk()label = tk.Label(root, text="Click me")
label.pack()
label.bind("<Button-1>", say_hello)root.mainloop()
 
https://img-blog.csdnimg.cn/be7ce4efc5664b5592a3d15dac4c63aa.png
14、为Toplevel组件(顶部操作杆)绑定回调函数
import tkinter as tkdef create_window():
    window = tk.Toplevel(root)
    label = tk.Label(window, text="New Window")
    label.pack()root = tk.Tk()button = tk.Button(root, text="Create window", command=create_window)
button.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/7fa4e3b243274c649e134abd92bf7f95.png
15、为Canvas中(画布)的图形对象设置鼠标样式
import tkinter as tkdef set_cursor(event):
    canvas.config(cursor="crosshair")root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
canvas.bind("<Motion>", set_cursor)canvas.pack()root.mainloop()
 
https://img-blog.csdnimg.cn/b100a3e27f364d0dbf35145ba2be21e0.png
16、为Entry组件绑定回调函数
import tkinter as tk
#   Python学习交流裙:708525271
def show_input(event):
    print("Input is:", entry.get())root = tk.Tk()entry = tk.Entry(root)
entry.bind("<Return>", show_input)entry.pack()
root.mainloop()
 
https://img-blog.csdnimg.cn/a8228bbdfb414910bec15ca408c55f6c.png
17、为Text组件设置快捷键
import tkinter as tkdef copy(event):
    text.event_generate("<Control-c>")root = tk.Tk()text = tk.Text(root)
text.bind("<Control-c>", lambda e: print("Copied!"))button = tk.Button(root, text="Copy", command=lambda: copy(None))
button.pack()text.pack() 
18、为Canvas中的图形对象添加标签
import tkinter as tkdef show_label(event):
    item = canvas.find_withtag("current")
    canvas.itemconfig(item, tags=("item", "selected"))
    canvas.itemconfig("label", text="Selected item: " + str(item))root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
rectangle = canvas.create_rectangle(50, 50, 100, 100, fill="blue", tags=("item"))
label = canvas.create_text(150, 20, text="No item selected", tags=("label"))canvas.bind("<Button-1>", show_label)canvas.pack()root.mainloop() 
验证程序能够运行,且可以显示在没有选择前、选择后。

 
https://img-blog.csdnimg.cn/660fbb3622f34f298e6ef36748bdc1b5.png
19、为Canvas中的图形对象设置动画效果
import tkinter as tkdef animate():
    canvas.move(rectangle, 2, 2)
    canvas.after(10, animate)root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
rectangle = canvas.create_rectangle(50, 50, 100, 100, fill="blue")animate()canvas.pack()root.mainloop() 
经过验证,程序可以运行,蓝色的图形会运动到右下角。

 
https://img-blog.csdnimg.cn/cb6880c2a8fa4154a4d2ec7a7d05f2e4.png
20、为Menu组件设置图片
import tkinter as tkroot = tk.Tk()menubar = tk.Menu(root)filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New", image=tk.PhotoImage(file="D:\\test\\test\\icons\\new.png"))
filemenu.add_command(label="Open", image=tk.PhotoImage(file="D:\\test\\test\\icons\\open.png"))
filemenu.add_command(label="Save", image=tk.PhotoImage(file="D:\\test\\test\\icons\\save.png"))
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)editmenu = tk.Menu(menubar, tearoff=0)
editmenu.add_command(label="Copy", image=tk.PhotoImage(file="D:\\test\\test\\icons\\copy.png"))
editmenu.add_command(label="Cut", image=tk.PhotoImage(file="D:\\test\\test\\icons\\cut.png"))
editmenu.add_command(label="Paste", image=tk.PhotoImage(file="D:\\test\\test\\icons\\paste.png"))helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="About", image=tk.PhotoImage(file="D:\\test\\test\\icons\\about.png"))menubar.add_cascade(label="File", menu=filemenu)
menubar.add_cascade(label="Edit", menu=editmenu)
menubar.add_cascade(label="Help", menu=helpmenu)root.config(menu=menubar)root.mainloop() 
程序测试好像不成功,没有找到原因

 
https://img-blog.csdnimg.cn/2d5d4a6d914241f68110915e55771575.png
21、为Canvas中的图形对象设置背景图片
import tkinter as tkroot = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
canvas.config(bg="white")photo = tk.PhotoImage(file="icons/background.png")
canvas.create_image(0, 0, image=photo, anchor="nw")canvas.pack()root.mainloop() 
22、为Canvas中的图形对象设置鼠标拖动效果
import tkinter as tkdef start_drag(event):
    global drag_pos
    drag_pos = (event.x, event.y)def drag(event):
    global drag_pos
    delta_x = event.x - drag_pos
    delta_y = event.y - drag_pos
    canvas.move(rectangle, delta_x, delta_y)
    drag_pos = (event.x, event.y)root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
rectangle = canvas.create_rectangle(50, 50, 100, 100, fill="blue")
canvas.tag_bind(rectangle, "<Button-1>", start_drag)
canvas.tag_bind(rectangle, "<B1-Motion>", drag)canvas.pack()root.mainloop() 
23、为Canvas中的图形对象设置点击特效
import tkinter as tkdef toggle_color(event):
    canvas.itemconfig(event.widget, fill="green" if event.widget in selected else "blue")
    if event.widget in selected:
      selected.remove(event.widget)
    else:
      selected.append(event.widget)root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)rectangles = []
selected = []for i in range(3):
    for j in range(3):
      rectangle = canvas.create_rectangle(i*100, j*100, i*100+50, j*100+50, fill="blue")
      canvas.tag_bind(rectangle, "<Button-1>", toggle_color)
      rectangles.append(rectangle)canvas.pack()root.mainloop() 
24、为Canvas中的图形对象设置缩放效果
import tkinter as tkdef zoom(delta):
    scale = 1.1 if delta > 0 else 0.9
    canvas.scale("all", 0, 0, scale, scale)root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
rectangle = canvas.create_rectangle(50, 50, 100, 100, fill="blue")
canvas.bind("<MouseWheel>", lambda e: zoom(e.delta))canvas.pack()root.mainloop() 
25、为Canvas中的图形对象设置旋转效果
import tkinter as tk
import mathdef rotate(delta):
    angle = math.radians(delta)
    rx, ry = canvas.coords(rectangle)[:2]
    cos = math.cos(angle)
    sin = math.sin(angle)
    x, y = canvas.coords(rectangle)
    tx = cos * (x-rx) - sin * (y-ry) + rx
    ty = sin * (x-rx) + cos * (y-ry) + ry
    canvas.coords(rectangle, rx, ry, tx, ty)root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)
rectangle = canvas.create_rectangle(50, 50, 100, 100, fill="blue")
canvas.bind("<MouseWheel>", lambda e: rotate(e.delta))canvas.pack()root.mainloop() 
26、为Canvas中的图形对象设置反色效果
import tkinter as tkdef toggle_color(event):
    pixels = canvas.itemcget(event.widget, "fill")
    if pixels == "blue":
      canvas.itemconfig(event.widget, fill="yellow")
    else:
      canvas.itemconfig(event.widget, fill="blue")root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)rectangles = []for i in range(3):
    for j in range(3):
      rectangle = canvas.create_rectangle(i*100, j*100, i*100+50, j*100+50, fill="blue")
      canvas.tag_bind(rectangle, "<Button-1>", toggle_color)
      rectangles.append(rectangle)canvas.pack()root.mainloop() 
27、为Canvas中的图形对象设置闪烁效果
import tkinter as tkdef start_blink(event):
    canvas.itemconfig(event.widget, fill="yellow")
    canvas.after(200, lambda: canvas.itemconfig(event.widget, fill="blue"))
    canvas.after(400, lambda: canvas.itemconfig(event.widget, fill="yellow"))
    canvas.after(600, lambda: canvas.itemconfig(event.widget, fill="blue"))root = tk.Tk()canvas = tk.Canvas(root, width=300, height=300)rectangles = []
                                                                                                                                                                                                                                                                                                                                                                                                         root.mainloop() 

 
https://img-blog.csdnimg.cn/e179f5ffb7e84315846c0e98eb417a3c.png
28、为Menu组件设置子菜单
import tkinter as tk

root = tk.Tk()

menubar = tk.Menu(root)

filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New")
filemenu.add_command(label="Open")
filemenu.add_command(label="Save")

subfilemenu = tk.Menu(filemenu, tearoff=0)
subfilemenu.add_command(label="Option 1")
subfilemenu.add_command(label="Option 2")

filemenu.add_cascade(label="More", menu=subfilemenu)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)

menubar.add_cascade(label="File", menu=filemenu)

root.config(menu=menubar)

root.mainloop()
 
https://img-blog.csdnimg.cn/5bac3ded5e0b4b5bafde9c642e0d0df4.png
29、为Canvas中的图形对象设置尺寸调整效果
import tkinter as tk

def start_resize(event):
    global resize_pos
    resize_pos = (event.x, event.y)
# Python学习交流扣裙 708525271
def resize(event):
    global resize_pos
    delta_x = event.x - resize_pos
    delta_y = event.y - resize_pos
    x, y, w, h = canvas.coords(rectangle)
    if event.widget == resize_left:
      canvas.coords(rectangle, x+delta_x, y, w-delta_x, h)
    elif event.widget == resize_top:
      canvas.coords(rectangle, x, y+delta_y, w, h-delta_y)
    elif event.widget == resize_right:
      canvas.coords(rectangle, x, y, w+delta_x, h)
    elif event.widget == resize_bottom:
      canvas.coords(rectangle, x, y, w, h+delta_y)
    resize_pos = (event.x, event.y)

root = tk.Tk()

canvas = tk.Canvas(root, width=300, height=300)
rectangle = canvas.create_rectangle(50, 50, 100, 100, fill="blue")

resize_left = tk.Canvas(canvas, width=10, height=10, bd=-2, bg="white", cursor="sb_h_double_arrow")
resize_top = tk.Canvas(canvas, width=10, height=10, bd=-2, bg="white", cursor="sb_v_double_arrow")
resize_right = tk.Canvas(canvas, width=10, height=10, bd=-2, bg="white", cursor="sb_h_double_arrow")
resize_bottom = tk.Canvas(canvas, width=10, height=10, bd=-2, bg="white", cursor="sb_v_double_arrow")

resize_left.place(x=50-5, y=75-5)
resize_top.place(x=75-5, y=50-5)
resize_right.place(x=100-5, y=75-5)
resize_bottom.place(x=75-5, y=100-5)

resize_left.bind("<Button-1>", start_resize)
resize_top.bind("<Button-1>", start_resize)
resize_right.bind("<Button-1>", start_resize)
resize_bottom.bind("<Button-1>", start_resize)

resize_left.bind("<B1-Motion>", resize)
resize_top.bind("<B1-Motion>", resize)
resize_right.bind("<B1-Motion>", resize)
resize_bottom.bind("<B1-Motion>", resize)

canvas.pack()

root.mainloop()
 
https://img-blog.csdnimg.cn/19ada6463bc54ff382f1adbc7c71ed0c.png
# 我给大家准备了25个非常实用的Python爬虫项目,帮助大家更好的学习爬虫。
# 大家也可根据项目的需求,自己构建解决方法,提高编程水平。
# 全套的python自学视频以及项目,已经打包完毕
# 都放在这个扣裙了 708525271 直接拿走学习了! 

 

 
https://img-blog.csdnimg.cn/6fc03fcabe18488abf0cf5e6c07417c4.png
https://img-blog.csdnimg.cn/2ba74d8d2e8a4f99a5faf3cf3d2f766c.png
代码整理不易,建议保存。
今天的分享就到这结束了,下次见!来源:https://www.cnblogs.com/hahaa/p/17437004.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Python丨tkinter开发常用的29种功能用法(建议码住)