午夜视频在线网站,日韩视频精品在线,中文字幕精品一区二区三区在线,在线播放精品,1024你懂我懂的旧版人,欧美日韩一级黄色片,一区二区三区在线观看视频

分享

Python GUI 編程:tkinter 初學(xué)者入門指南——按鈕

 信息科技云課堂 2024-09-30 發(fā)布于山東

在本文中,您將了解 tkinter Button 小部件以及如何使用它來(lái)創(chuàng)建各種按鈕。

Button 小部件用于顯示可點(diǎn)擊的按鈕,可以將它們配置為在單擊它們時(shí)調(diào)用類的函數(shù)或方法。

要?jiǎng)?chuàng)建按鈕,請(qǐng)按如下方式使用構(gòu)造函數(shù):

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

按鈕有很多選項(xiàng),command 參數(shù)指定一個(gè)回調(diào)函數(shù),該函數(shù)將在單擊按鈕時(shí)自動(dòng)調(diào)用。

Tkinter 按鈕示例

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

# 此處設(shè)置按鈕

def callback():
    pass


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

也可以直接調(diào)用部分命令,不使用自定義函數(shù)。

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

# 此處設(shè)置按鈕
button = tk.Button(
   root, 
   text="退出"
   command=root.destroy
)
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()

Tkinter 圖像按鈕示例

可以在按鈕上顯示一個(gè)圖片。

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

# 此處設(shè)置按鈕
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()

如果同時(shí)顯示圖片和文字,可以添加參數(shù):compound。

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

# 此處設(shè)置按鈕
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 按鈕其他選項(xiàng)

import tkinter as tk
root = tk.Tk()
root.geometry('300x200+200+200')
root.title('Button 按鈕演示')
def callback():
    pass
# 此處設(shè)置按鈕
button = tk.Button(
    root, 
    text="Click Me"
    command=callback,
    activebackground="blue"# 按鈕按下時(shí)的顏色
    activeforeground="white"# 按鈕按下時(shí)文字顏色
    bd=1# 按鈕邊框?qū)挾?/span>
    bg="lightgray"# 按鈕背景色
    cursor="hand2"# 鼠標(biāo)指針樣式
    fg="black"# 文字顏色
    font=("Arial"12), # 文字字體字號(hào)
    height=2# 按鈕高度
    justify="center"# 對(duì)齊方式
    padx=10# 文字左右邊距
    pady=5# 文字上下邊距
    width=15# 按鈕寬度
    wraplength=100 # 文本換行
    ) 
button.pack(ipadx=5, ipady=5, expand=True)
root.mainloop()

    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多