首页 > 编程语言 >Python丨tkinter开发常用的29种功能用法(建议码住)

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

时间:2023-05-27 17:11:36浏览次数:34  
标签:canvas tkinter Python 码住 label command tk root event

在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()

 

2、为Checkbutton组件(多选择钮)绑定回调函数

import tkinter as tk

def 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()

 

3、为Radiobutton组件(单选择钮)绑定回调函数

import tkinter as tk

def 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()

 

4、为Listbox组件(列表组件)绑定回调函数

import tkinter as tk

def 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()

 

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组件

 

6、为Scale组件(滑条)绑定回调函数

import tkinter as tk

def 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()

 

7、为Scrollbar组件(滚动条)绑定回调函数

import tkinter as tk

def 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()

 

8、为Canvas组件(画布)绑定回调函数

import tkinter as tk

def 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()

 

9、为Text组件(文本框)绑定回调函数

import tkinter as tk

def 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()

 

10、为Menu组件(菜单)绑定回调函数

import tkinter as tk

def 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()

 

11、为Canvas(画布)中的图形对象绑定回调函数

import tkinter as tk

def 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()

 

当点击蓝色方块时,蓝色方块会移动

12、为Frame组件绑定回调函数

import tkinter as tk

def 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()

 

13、为Label组件(标签)绑定回调函数

import tkinter as tk

def 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()

 

14、为Toplevel组件(顶部操作杆)绑定回调函数

import tkinter as tk

def 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()

 

15、为Canvas中(画布)的图形对象设置鼠标样式

import tkinter as tk

def 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()

 

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()

 

17、为Text组件设置快捷键

import tkinter as tk

def 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 tk

def show_label(event):
    item = canvas.find_withtag("current")
    canvas.itemconfig(item, tags=("item", "selected"))
    canvas.itemconfig("label", text="Selected item: " + str(item[0]))

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()

 

验证程序能够运行,且可以显示在没有选择前、选择后。

 

19、为Canvas中的图形对象设置动画效果

import tkinter as tk

def 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()

 

经过验证,程序可以运行,蓝色的图形会运动到右下角。

 

20、为Menu组件设置图片

import tkinter as tk

root = 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()

 

程序测试好像不成功,没有找到原因

 

21、为Canvas中的图形对象设置背景图片

import tkinter as tk

root = 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 tk

def start_drag(event):
    global drag_pos
    drag_pos = (event.x, event.y)

def drag(event):
    global drag_pos
    delta_x = event.x - drag_pos[0]
    delta_y = event.y - drag_pos[1]
    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 tk

def 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 tk

def 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 math

def 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)[2:4]
    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 tk

def 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 tk

def 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()

 



 

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()

 

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[0]
    delta_y = event.y - resize_pos[1]
    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()

 

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

 

 

 


代码整理不易,建议保存。

今天的分享就到这结束了,下次见!

标签:canvas,tkinter,Python,码住,label,command,tk,root,event
From: https://www.cnblogs.com/hahaa/p/17437004.html

相关文章

  • 花朵识别系统Python实现,基于深度学习卷积神经网络算法
    一、背景花朵识别系统,基于Python实现,深度学习卷积神经网络,通过TensorFlow搭建卷积神经网络算法模型,并对数据集进行训练最后得到训练好的模型文件,并基于Django搭建可视化操作平台。在当今信息化社会,图像识别技术在各种领域都展现出了重要的应用价值,包括医学影像分析、自动驾驶、人脸......
  • python内置库--hashlib
    1关于hashlib与hash算法python的hashlib提供了对hash算法的的支持,常见的算法有MD5SHA1SHA224等,对不同的算法,hashlib提供了一些通用的函数,以方便我们的使用hash算法个人理解是,它可以将任意长度的二进制值变为固定长度的二进制值。通常,这个固定长度的二进制值叫做hash值,也叫......
  • Python格式化字符串
    Python为我们提供了四种格式化字符串的办法,分别是:%运算符字符串format格式化字符串字面值模板字符串%运算符这种方法最常见,简单略过s="Thisis%s'sblog"%"结了冰的可乐"print(s)使用%运算符格式化字符串的语法是format%values。format是一个字符串,values可以......
  • Python 列表使用
    一、列表推导式(1)条件推导式value1:如果条件表达式condition成立,返回value1;如果条件表达式不成立,返回value2;condition:条件表达式Value2:如果条件表达式condition成立,返回value1;如果条件表达式不成立,返回value2;value1ifconditionelseValue2如,判断一个数是偶数......
  • 配置 Orchestra Python API
    简介:OrchestraPythonAPI是开发者构建本地工具链的定海神针,你可以轻而易举的把它集成到制作流程中,拓展自身业务的边界。OrchestraPythonAPI与网页端接口高度同构,不仅易于理解和使用,还兼容python2.7至3.11的版本。OrchestraPythonAPI工具并不附带Python运行环境......
  • 如何通过Python将JSON格式文件导入redis?
    摘要:如果希望将JSON文件导入到Redis中,首先要做的就是连接到redis服务。本文分享自华为云社区《Python将JSON格式文件导入redis,多种方法》,作者:梦想橡皮擦。在导入前需要先确定你已经安装Redis,并且可以启动相关服务。windows上启动redis的命令是redis-server.exer......
  • python循环怎么执行不了
    在Python编程中,循环是一种重要的语句类型,可以让我们对一组数据进行重复的操作。如果您的循环无法正常执行,可能会有多种原因。下面是一些可能导致循环无法正常执行的原因和解决方法:循环条件不满足:循环语句的执行需要满足一定的条件,如果条件不满足,循环就不会执行。请检查您的循......
  • Python相关性分析代码
    进行相关性分析的代码主要涉及数据处理和统计分析。以下是使用Python进行相关性分析的一般步骤:1.导入必要的库:importpandasaspdimportnumpyasnpimportseabornassnsimportmatplotlib.pyplotasplt2.读取数据:将你的数据加载到PandasDataFrame中。data=pd.read_c......
  • 01python环境安装 conda + vscode
    conda安装win10安装1、从官网下载python版本对应的miniconda;2、一直Next;不用配置环境变量;修改安装路径,因为后面创建的虚拟环境是放在安装目录;3、安装后,打开AnacondaPrompt即可使用;4、配置镜像(国内下载太慢,还容易卡住)Windows用户无法直接创建名为.condarc的文件,可先生成......
  • Python项目如何打包?
    在Python中,你可以使用一些工具和技术来打包你的项目,以便于分发和部署。以下是一种常见的方法:1.创建项目结构:首先,你需要组织好你的项目结构。一个常见的做法是创建一个包含项目代码的文件夹,并在其中包含一个名为__init__.py的文件,以将其标识为Python包。2.编写setup.py文件:s......