您的位置:首页技术文章
文章详情页

Python Tkinter实例——模拟掷骰子

【字号: 日期:2022-07-07 10:57:07浏览:4作者:猪猪

什么是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实例——模拟掷骰子

总结:

非常简单的小程序,适合初学者入门。 

以上就是Python Tkinter实例——模拟掷骰子的详细内容,更多关于Python Tkinter的资料请关注好吧啦网其它相关文章!

标签: Python 编程
相关文章: