Python tkinter doesnt start

Thread Starter

Samantha Groves

Joined Nov 25, 2023
151
Hi.I have this code:

Python:
import socket
import threading
from tkinter import *
from tkinter import messagebox

port = 2222

filename = 'records.txt'

file = open(filename, 'a')

clients = []

window = Tk()

window.maxsize(100, 100)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.bind((socket.gethostname(), port))

sock.listen()


def listen():
    while True:

        client, address = sock.accept()

        response = messagebox.askyesno('You have a new request', address)

        if response == 'No':

            client.close()

            record = str(address) + ':' + 'access rejected'

            file.write(record)



        else:

            clients.append(client)

            record = str(address) + ':' + 'access granted'

            file.write(record)


listen()

window.mainloop()
What troubles is that the window isnt created when trying to run this,how do I solve this?
 

be80be

Joined Jul 5, 2008
2,394
your code won't work as expected because the listen() function contains an infinite loop with a blocking call, sock.accept(). This call freezes the program until a client connects, preventing the window.mainloop() line from ever being reached. Without mainloop(), the Tkinter window will never appear.
this should fix it


Python:
import socket
import threading
from tkinter import *
from tkinter import messagebox

# --- Configuration ---
PORT = 2222
FILENAME = 'records.txt'
clients = []

# --- Set up the server socket ---
# The server will listen for connections on all available interfaces
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind(('', PORT)) # Use '' for INADDR_ANY
server_sock.listen()

print(f"✅ Server is listening on port {PORT}...")

# --- Networking Logic ---
def listen_for_connections():
    """
    Runs in a background thread to accept new client connections
    without freezing the GUI.
    """
    while True:
        try:
            # This call blocks until a client connects
            client_socket, address = server_sock.accept()
            addr_str = f"{address[0]}:{address[1]}"
            print(f"Incoming connection from {addr_str}")

            # Ask the user for permission via the main thread's GUI
            response = messagebox.askyesno('New Connection Request', f'Accept connection from {addr_str}?')

            record = ""
            if response: # True if user clicks 'Yes'
                clients.append(client_socket)
                record = f"{addr_str}: access granted\n"
                print(f"Connection from {addr_str} accepted.")
            else:
                client_socket.close()
                record = f"{addr_str}: access rejected\n"
                print(f"Connection from {addr_str} rejected.")

            # Safely write the record to the file
            with open(FILENAME, 'a') as file:
                file.write(record)

        except OSError:
            # This will happen when the main program closes the socket
            break

# --- GUI Setup ---
window = Tk()
window.title("Server Control")
window.geometry("300x150")

# Label to show server status
Label(window, text=f"Server running on port {PORT}", font=("Helvetica", 12)).pack(pady=20)

def on_closing():
    """Handles window close event to shut down gracefully."""
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        server_sock.close() # Close the server socket to unblock the listening thread
        window.destroy()

# Set the window close protocol
window.protocol("WM_DELETE_WINDOW", on_closing)

# --- Start the Application ---
# Create and start the background thread for listening
# daemon=True ensures the thread will close when the main program exits
listener_thread = threading.Thread(target=listen_for_connections, daemon=True)
listener_thread.start()

# Start the GUI event loop (this is a blocking call)
window.mainloop()

print("Server has shut down.")
 
Top