嗨喽,大家好呀~这里是爱看美女的茜茜呐
在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组件(多选择钮)绑定回调函数
'''
python资料获取看这里噢!! 小编 V:Pytho8987(记得好友验证备注:6 笔芯~)
即可获取:文章源码/教程/资料/解答等福利,还有不错的视频学习教程和PDF电子书!
'''
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组件(列表组件)绑定回调函数
'''
python资料获取看这里噢!! 小编 V:Pytho8987(记得好友验证备注:6 笔芯~)
即可获取:文章源码/教程/资料/解答等福利,还有不错的视频学习教程和PDF电子书!
'''
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
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组件(滚动条)绑定回调函数
'''
python资料获取看这里噢!! 小编 V:Pytho8987(记得好友验证备注:6 笔芯~)
即可获取:文章源码/教程/资料/解答等福利,还有不错的视频学习教程和PDF电子书!
'''
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", ""<