Python Tkinter實例——模擬擲骰子
什么是Tkinter?
Tkinter 是 Python 的標準 GUI 庫。Python 使用 Tkinter 可以快速的創(chuàng)建 GUI 應用程序。
由于 Tkinter 是內置到 python 的安裝包中、只要安裝好 Python 之后就能 import Tkinter 庫、適合初學者入門、小型應用的開發(fā) 。簡單的代價就是功能薄弱了,有相當多的需求需要依賴其他的庫。不像PyQT、wxPython這些功能強大的框架。
需要導入的模塊
- Tkinter:建立圖形界面
- Random:生成隨機數(shù)
- Image,Imagetk:從PIL導入,即Python Imaging Library。我們使用它來執(zhí)行涉及UI中圖像的操作
import tkinter from PIL import Image, ImageTk import 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)在我們每次運行程序將得到一個隨機骰子點數(shù)的圖像
說明
expand聲明為true,即使調整窗口大小,圖像也始終保留在中心
創(chuàng)建按鈕,模擬擲骰子
# 添加按鈕所實現(xiàn)的功能 def rolling_dice(): diceimage = ImageTk.PhotoImage(Image.open (random.choice(dice))) # 更新圖片 label1.configure(image=diceimage) label1.image = diceimage # 添加按鈕 設置按鈕樣式 實現(xiàn)上面所定義的功能 button = tkinter.Button(root, text='擲骰子', fg='red', command=rolling_dice) # 放置在窗口中 button.pack( expand=True)

總結:
非常簡單的小程序,適合初學者入門?!?/p>
以上就是Python Tkinter實例——模擬擲骰子的詳細內容,更多關于Python Tkinter的資料請關注腳本之家其它相關文章!
相關文章
詳解Python?itertools模塊中starmap函數(shù)的應用
starmap是一個非常有用的函數(shù),它屬于itertools模塊中的一部分,本文將詳細介紹starmap函數(shù)的作用、用法以及實際應用場景,希望對大家有所幫助2024-03-03
pytorch中torch.max和Tensor.view函數(shù)用法詳解
今天小編就為大家分享一篇pytorch中torch.max和Tensor.view函數(shù)用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python數(shù)學建模之Numpy?應用介紹與Pandas學習
這篇文章主要介紹了python數(shù)學建模之Numpy?應用介紹與Pandas學習,NumPy?是一個運行速度非??斓臄?shù)學庫,一個開源的的python科學計算庫,主要用于數(shù)組、矩陣計算2022-07-07

