骰子是很多游戏必不可少的道具,虽然用代码模拟生成骰子的点数比较简单,但在图形化的游戏里,如果能够模拟出掷骰子的效果,必然会为游戏增色不少。正好最近问哥在琢磨的几个小游戏都需要用到掷骰子,于是单独写篇文章把掷骰子这个小功能的实现方法单独拿出来。
效果
![](https://img-blog.csdnimg.cn/33af3817d1b6476789b9eee2655bee53.gif)
代码实现起来也比较简单,因为问哥是用python的内置模块tkinter实现的GUI,所以代码也是使用tkinter编写。
代码实现
from tkinter import *
import random
root = Tk()
root.geometry('200x250')
root.title('掷骰子')
dice_rotate = [PhotoImage(file=r'images\donghua.gif', format=f'gif -index {i}') for i in range(13)]
dice = [PhotoImage(file=f'images/{i}.png') for i in range(1,7)]
i = 0
def rotate():
global i
if i=12,就不再运行after函数,而是展现一张静态的骰子图片,用来表示掷骰子的结果,最后把计数器归零。
i = 0
def rotate():
global i # 全局变量计数器
if i |