您的位置:首頁技術文章
文章詳情頁

Python Tkinter實例——模擬擲骰子

瀏覽:4日期:2022-07-07 10:57:07

什么是Tkinter?

Tkinter 是 Python 的標準 GUI 庫。Python 使用 Tkinter 可以快速的創建 GUI 應用程序。

由于 Tkinter 是內置到 python 的安裝包中、只要安裝好 Python 之后就能 import Tkinter 庫、適合初學者入門、小型應用的開發 。簡單的代價就是功能薄弱了,有相當多的需求需要依賴其他的庫。不像PyQT、wxPython這些功能強大的框架。

需要導入的模塊

Tkinter:建立圖形界面 Random:生成隨機數 Image,Imagetk:從PIL導入,即Python Imaging Library。我們使用它來執行涉及UI中圖像的操作

import tkinterfrom PIL import Image, ImageTkimport random

創建主程序窗口

# 創建主窗口root = tkinter.Tk()root.geometry(’400x400’)root.title(’擲骰子’)

Python Tkinter實例——模擬擲骰子

如圖所示,創建了一個圖形界面窗口

在窗口中添加圖像顯示區域

# 圖片文件dice = [’die1.png’, ’die2.png’, ’die3.png’, ’die4.png’, ’die5.png’, ’die6.png’]# 使用隨機數模擬骰子并生成圖像diceimage = ImageTk.PhotoImage(Image.open(random.choice(dice)))label1 = tkinter.Label(root, image=diceimage)label1.image = diceimage# 放置在窗口中 label1.pack(expand=True)

現在我們每次運行程序將得到一個隨機骰子點數的圖像

說明

expand聲明為true,即使調整窗口大小,圖像也始終保留在中心

創建按鈕,模擬擲骰子

# 添加按鈕所實現的功能def rolling_dice(): diceimage = ImageTk.PhotoImage(Image.open (random.choice(dice))) # 更新圖片 label1.configure(image=diceimage) label1.image = diceimage# 添加按鈕 設置按鈕樣式 實現上面所定義的功能button = tkinter.Button(root, text=’擲骰子’, fg=’red’, command=rolling_dice)# 放置在窗口中button.pack( expand=True)

Python Tkinter實例——模擬擲骰子

總結:

非常簡單的小程序,適合初學者入門?!?/p>

以上就是Python Tkinter實例——模擬擲骰子的詳細內容,更多關于Python Tkinter的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区