1
我终于完成了我一直在努力的一个骰子滚动程序,并且我想添加一件最后一件事:我想添加一个说“滚动骰子”的按钮。有没有办法用Tkinter按钮来运行Python脚本?我试过使用:如何使用Tkinter按钮来运行Python脚本?
from tkinter import *
master = Tk()
def callback():
CODE HERE
b = Button(master, text="BUTTON TEXT", command=callback)
b.pack()
mainloop()
但是当我使用它时,pygame窗口只是黑色。
我的程序代码是:
exec(open("Dice Crop.py").read(), globals())
from pygame.locals import *
from random import randint
from tkinter import *
import pygame
import sys
pygame.init()
font = pygame.font.SysFont("comicsansms",30)
screen = pygame.display.set_mode((284,177),0,32)
background = pygame.image.load("background.jpg").convert()
one = pygame.image.load("one.png").convert_alpha()
two = pygame.image.load("two.png").convert_alpha()
three = pygame.image.load("three.png").convert_alpha()
four = pygame.image.load("four.png").convert_alpha()
five = pygame.image.load("five.png").convert_alpha()
six = pygame.image.load("six.png").convert_alpha()
counter = 0
while True:
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.blit(background,(0, 0))
if counter < 20:
n = randint(1,6)
counter += 1
if n == 1:
screen.blit(one,(100,50))
screen.blit(font.render("1",True,(0,200,0)),(125,130))
if n == 2:
screen.blit(two,(100,50))
screen.blit(font.render("2",True,(0,200,0)),(125,130))
if n == 3:
screen.blit(three,(100,50))
screen.blit(font.render("3",True,(0,200,0)),(125,130))
if n == 4:
screen.blit(four,(100,50))
screen.blit(font.render("4",True,(0,200,0)),(125,130))
if n == 5:
screen.blit(five,(100,50))
screen.blit(font.render("5",True,(0,200,0)),(125,130))
if n == 6:
screen.blit(six,(100,50))
screen.blit(font.render("6",True,(0,200,0)),(125,130))
if counter < 20:
print(n)
if counter == 20:
print(">",n,"<")
pygame.time.delay(100)
pygame.display.update()
(所有exec(open("Dice Crop.py").read(), globals())
确实是开放的一个Python脚本,需要与多个骰子和切片成单独的图像一个图像)
通过pygame.Rect及其碰撞检测方法可以很容易地在pygame中创建一个非常简单的按钮。你不需要tkinter。你必须执行另一个Python脚本也很奇怪。切片图像是你可以用pygame做的事情,如果你想在另一个文件中做,那么你应该导入切片图像,而不是执行文件。 – skrx
我已经用'pygame.Rect'发布了一个解决方案,但是我会检查一下tkinter是否也可以实现。但是,我不知道pygame和tkinter是如何协同工作的。 – skrx
[这是一个答案](https://stackoverflow.com/a/16550818/6220679),告诉你如何将一个pygame显示嵌入到tkinter.Frame中,但它有点奇怪,我宁愿使用pygame的GUI库(如[SGC](http://pygame.org/project-SGC-2089-4505.html))或者只是一个矩形。 – skrx