Tkinter和Pygame集成在一个窗口中,光标闪烁

时间:2019-01-16 19:20:01

标签: python tkinter pygame

下面是一些我正在测试的代码,用于将Tkinter和Pygame集成在一起。我设法在Tkinter窗口中显示了一个pygame,并在该pygame的显示上方显示了一个按钮。该按钮仅绘制一个白色圆圈。通过在程序启动时不绘制Tkinter的已配置光标(X_cursor),可立即开始问题。然后,当我将鼠标悬停在按钮上并从其上移开时,光标开始闪烁到pygame的默认光标,然后又回到Tkinter的已配置光标。另外,如果鼠标在运动中,光标只会恢复为pygame的默认值。否则,它是正确的“ X_Cursor”。

我很难理解Tkinter的系统,而且我确定解决方案就在我眼前。我只需要一点帮助就可以解决这个问题。

import pygame
import pygame.key
from pygame.locals import *
import tkinter as tk
from tkinter import *
import os


#colors#
BLACK = (0,0,0)
WHITE = (255, 255, 255)
GREEN = (0, 255,0)
RED = (255, 0,0)
BLUE = (0,0, 255)

#buttons#
mButton1 = (1, 0, 0)
mButton2 = (0, 1, 0)
mButton3 = (0, 0, 1)



root = tk.Tk()
root.attributes('-fullscreen', True)
root.title("This title isn't visible since it's fullscreen")
root.config(cursor = "X_cursor")

embed = tk.Frame(root, width = 1920, height = 1080) #creates embed frame for pygame window
embed.grid(columnspan = 10, rowspan = 10) # Adds grid



os.environ['SDL_WINDOWID'] = str(embed.winfo_id())


worldWindow = pygame.display.set_mode((0,0), RESIZABLE)
worldWindow.fill(BLACK)


def draw():
    pygame.draw.circle(worldWindow, WHITE, (250,250), 125)

IMAGEOBJECT = PhotoImage( file = 'TESTIMAGE.gif')


buttonwin = tk.Frame(root, width = 75, height = 75)
buttonwin.grid(row =8, column = 8)
button1 = Button(root, image = IMAGEOBJECT,text = "Draw a circle", cursor = "circle",  command=draw)
button1.grid(row =8 , column = 8)



pygame.display.init()

#loop until user clicks close button
done = False

clock = pygame.time.Clock()

#~~~~~~~~MAIN LOOP~~~~~~~~#
while not done:
    for event in pygame.event.get():
        if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and pygame.K_ESCAPE):
            done = True
        elif event.type == pygame.MOUSEBUTTONDOWN:  
            mButton = pygame.mouse.get_pressed()
            if mButton == mButton1:
                pos = pygame.mouse.get_pos()
                print(pos)

        else:
            pygame.event.clear()

    #limit to 60 frames per second
    clock.tick(60)

    #update the screen with all the draws
    pygame.display.update()
    root.update()
pygame.quit()

1 个答案:

答案 0 :(得分:3)

似乎是tkinter和pygame争夺谁显示了光标。我将此添加到pygame事件循环中进行检查。

elif event.type == pygame.MOUSEMOTION:
        pygame.mouse.set_cursor(*pygame.cursors.diamond)

行为保持不变,现在在移动时显示菱形光标,在停止时显示“ X”光标。当我注释掉tkinter光标配置时,然后在停止运动时获取Windows os默认光标。

在我看来,最简单的解决方案是将tkinter'X'加载到pygame光标编译器中,并将其作为默认值或在Mouse motion事件下使用(详细信息在链接中)。

https://www.pygame.org/docs/ref/cursors.html

我有点喜欢它的外观的另一种选择是在鼠标移动精灵中使用此光标。

*pygame.cursors.broken_x