程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python GUI 编程:tkinter 初学者入门指南——按钮

hfteth 2024-12-16 13:20:12 技术文章 60 ℃

在本文中,您将了解 tkinter Button 小部件以及如何使用它来创建各种按钮。

Button 小部件用于显示可点击的按钮,可以将它们配置为在单击它们时调用类的函数或方法。

要创建按钮,请按如下方式使用构造函数:

button = tk.Button(master, **option)

按钮有很多选项,command 参数指定一个回调函数,该函数将在单击按钮时自动调用。

Tkinter 按钮示例

import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按钮演示')

# 此处设置按钮

def callback():
    pass


button = tk.Button(
   root, 
   text="按钮演示", 
   command=callback
)
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()

也可以直接调用部分命令,不使用自定义函数。

import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按钮演示')

# 此处设置按钮
button = tk.Button(
   root, 
   text="退出", 
   command=root.destroy
)
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()

Tkinter 图像按钮示例

可以在按钮上显示一个图片。

import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按钮演示')

# 此处设置按钮
download_icon = tk.PhotoImage(file='Exit.png')
button = tk.Button(
   root,
   image=download_icon,
   text="退出", 
   command=root.destroy
)
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()

如果同时显示图片和文字,可以添加参数:compound。

import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按钮演示')

# 此处设置按钮
download_icon = tk.PhotoImage(file='Exit.png')
button = tk.Button(
   root,
   image=download_icon,
   text="退出", 
   command=root.destroy,
   compound=tk.TOP,
   font=("Arial", 20)
)
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()

Tkinter 按钮其他选项

import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按钮演示')
def callback():
    pass
# 此处设置按钮
button = tk.Button(
    root, 
    text="Click Me", 
    command=callback,
    activebackground="blue", # 按钮按下时的颜色
    activeforeground="white", # 按钮按下时文字颜色
    bd=1, # 按钮边框宽度
    bg="lightgray", # 按钮背景色
    cursor="hand2", # 鼠标指针样式
    fg="black", # 文字颜色
    font=("Arial", 12), # 文字字体字号
    height=2, # 按钮高度
    justify="center", # 对齐方式
    padx=10, # 文字左右边距
    pady=5, # 文字上下边距
    width=15, # 按钮宽度
    wraplength=100 # 文本换行
    ) 
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()

Tags:

最近发表
标签列表