0

I'm trying to configure a label's text to say "Connecting..." when a button is pressed, ping a website, then change the label to say "connection successful.

Here's the code I've been trying (it is all within the init of a class):

        #Connect button
        def connect_command():
            self.subHeading.configure(text="Connecting...")
            response = subprocess.run(["ping","google.com"], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
            if response.returncode == 0:
                self.subHeading.configure(text="Connection to google.com successful")
            else:
                self.subHeading.configure(text="Connection to google.com unsuccessful")
        self.connectButton = tk.Button(text="Connect", font=("calibri","15"), command = connect_command)
        self.connectButton.pack()

        self.subHeading = tk.Label()
        self.subHeading.pack()

However when this is run, the label doesn't change until after the site has been pinged, not showing "connecting..." at all, going straight to the "connection successful".

Any ideas on why it's not changing the label?

  • 2
    Because tkinter is event driven, no GUI changes actually take effect until your handler returns and the app gets back to its `mainloop`. `subprocess.run` does not return until the process completes, so your GUI is frozen the whole time. It's a fair amount of work to do that asynchronously. You'd have to use `Popen`, and use an `after` callback to check the status of the request. – Tim Roberts Jul 20 '22 at 17:56
  • Thank you. I had seen Popen somewhere but didn't know how it could be used. – brixt01 Jul 20 '22 at 18:03
  • If you don't mind the waiting on `subprocess.run()`, you can simply add `self.subHeading.update_idletasks()` to force tkinter to handle the pending updates before running `subprocess.run()`. – acw1668 Jul 21 '22 at 05:54

0 Answers0