Python Tkinter实例——模拟掷骰子

2020-10-28 0 334

什么是Tkinter?

Tkinter 是 Python 的标准 GUI 库。Python 使用 Tkinter 可以快速的创建 GUI 应用程序。

由于 Tkinter 是内置到 python 的安装包中、只要安装好 Python 之后就能 import Tkinter 库、适合初学者入门、小型应用的开发 。简单的代价就是功能薄弱了,有相当多的需求需要依赖其他的库。不像PyQT、wxPython这些功能强大的框架。

需要导入的模块

  • Tkinter:建立图形界面
  • Random:生成随机数
  • Image,Imagetk:从PIL导入,即Python Imaging Library。我们使用它来执行涉及UI中图像的操作
import tkinter
from PIL import Image, ImageTk
import 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 Python Tkinter实例——模拟掷骰子 http://www.ox520.com/27442.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务