Python Tkinter實例——模擬擲骰子
什么是Tkinter?
Tkinter 是 Python 的標(biāo)準(zhǔn) GUI 庫。Python 使用 Tkinter 可以快速的創(chuàng)建 GUI 應(yīng)用程序。
由于 Tkinter 是內(nèi)置到 python 的安裝包中、只要安裝好 Python 之后就能 import Tkinter 庫、適合初學(xué)者入門、小型應(yīng)用的開發(fā) 。簡單的代價就是功能薄弱了,有相當(dāng)多的需求需要依賴其他的庫。不像PyQT、wxPython這些功能強大的框架。
需要導(dǎo)入的模塊
Tkinter:建立圖形界面 Random:生成隨機數(shù) Image,Imagetk:從PIL導(dǎo)入,即Python Imaging Library。我們使用它來執(zhí)行涉及UI中圖像的操作import tkinterfrom PIL import Image, ImageTkimport random
創(chuàng)建主程序窗口
# 創(chuàng)建主窗口root = tkinter.Tk()root.geometry(’400x400’)root.title(’擲骰子’)
如圖所示,創(chuàng)建了一個圖形界面窗口
在窗口中添加圖像顯示區(qū)域
# 圖片文件dice = [’die1.png’, ’die2.png’, ’die3.png’, ’die4.png’, ’die5.png’, ’die6.png’]# 使用隨機數(shù)模擬骰子并生成圖像diceimage = ImageTk.PhotoImage(Image.open(random.choice(dice)))label1 = tkinter.Label(root, image=diceimage)label1.image = diceimage# 放置在窗口中 label1.pack(expand=True)
現(xiàn)在我們每次運行程序?qū)⒌玫揭粋€隨機骰子點數(shù)的圖像
說明
expand聲明為true,即使調(diào)整窗口大小,圖像也始終保留在中心
創(chuàng)建按鈕,模擬擲骰子
# 添加按鈕所實現(xiàn)的功能def rolling_dice(): diceimage = ImageTk.PhotoImage(Image.open (random.choice(dice))) # 更新圖片 label1.configure(image=diceimage) label1.image = diceimage# 添加按鈕 設(shè)置按鈕樣式 實現(xiàn)上面所定義的功能button = tkinter.Button(root, text=’擲骰子’, fg=’red’, command=rolling_dice)# 放置在窗口中button.pack( expand=True)
總結(jié):
非常簡單的小程序,適合初學(xué)者入門?!?/p>
以上就是Python Tkinter實例——模擬擲骰子的詳細(xì)內(nèi)容,更多關(guān)于Python Tkinter的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 解決Python 進程池Pool中一些坑2. Python如何讀寫CSV文件3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. 三個不常見的 HTML5 實用新特性簡介5. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁6. ajax請求添加自定義header參數(shù)代碼7. php測試程序運行速度和頁面執(zhí)行速度的代碼8. Python獲取抖音關(guān)注列表封號賬號的實現(xiàn)代碼9. python利用os模塊編寫文件復(fù)制功能——copy()函數(shù)用法10. Python使用jupyter notebook查看ipynb文件過程解析
