Python tkinter askopenfilename() not opening and responding

Viewed 341

Python tkinter askopenfilename() is not opening and responding. I searched and tried everything but it didn't work.

What's wrong?

Code:

from tkinter.filedialog import askopenfilenames
import pygame, keyboard, time
import tkinter as tk
from tkinter.filedialog import askopenfilename

from pygame import key
pygame.init()
pygame.mixer.init()
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 450
BLACK = (0, 0, 0)
pyscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.RESIZABLE)
def play(): 
    tkscreen = tk.Tk()
    tkscreen.iconbitmap("void.ico")
    tkscreen.title("Select music file...")
    print("b")
    global music
    tkscreen.update()
    music = askopenfilename() # Not responding!!
    tkscreen.update()
    print("c")
    try:
        pygame.mixer.music.load(music)
        print("d")
        pygame.mixer.music.play()
        print("e")
    except:
        print("e-1")
        print(f"{music} is not a music file. ")
print("a")
play()
pausecooldown = True
paused = False
while True:
    if keyboard.is_pressed("f9"):
        if keyboard.is_pressed("space") and pausecooldown:
            if paused:
                pygame.mixer.music.unpause()
                paused = False
                time.sleep(0.1)
                pausecooldown = False
            elif not paused:
                pygame.mixer.music.pause()
                paused = True
                time.sleep(0.1)
                pausecooldown = False
        pausecooldown = True
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            exit()

Version: Python 3.9.1

OS: Windows 10 Home

It prints 'b', and opens tkinter and pygame window, but 'Select file' window is not opening, and tkinter and pygame window is not responding.

2 Answers

I found an answer:

Every tkinter instance requires a mainloop() method to be run. This method essentially monitors what's happening with the app and reacts to user inputs. Without it, Tkinter just doesn't work. You can add tkscreen.mainloop() just before the first try block and it should hopefully solve issues.

from above comment (by pavel)

I know and can understand your problem.

I was doing a Tkinter project once. Well there is no better solution to this. BUT I can help you with this anyways.


I have two solutions which I would like to share it with you.

1. Using Debugger I used this solution for the program when I was just editing my program. If you use an IDE like VS Code or Pycharm. Run the code in Debugger mode. The program would work and respond.

It will work as wanted.

2. Using .exe file of the project Use this link to understand how to do that. It will just make your python program run as an application and as per me when I did this, the problem you mentioned didn't come up.

https://datatofish.com/executable-pyinstaller/


If you still get any problem, please comment below and ask anything you want.

Related