简体   繁体   中英

How to make program run after clicking the button tkinter

I`ve a problem that the program does not start after clicking the start button, but when the tkinter window is closed it starts. How can I make it working right after the button is clicked? Thought it could be because it writes it in a txt file, but shell print does not work eather.


from turtle import color
import time
import psutil
from tkinter import *


root = Tk()             
 
# Open window having dimension 900x600 and red colour
root.geometry('900x600')
root.configure(bg='black')
# ints for monitoring
last_received = psutil.net_io_counters().bytes_recv
last_sent = psutil.net_io_counters().bytes_sent
last_total = last_received + last_sent
running = False
a=1

#Define a function to start the programm
def start_monitorting():
        global running
        running = True
        

def stop_monitorting():
    global running
    running = False
    

# Create a Button
start_button = Button(root, text = 'Start Monitoring',height=5, width=50, fg='red', bg='grey',
                          command = start_monitorting)
stop_button = Button(root, text = 'Start Monitoring',height=a, width=50, fg='red', bg='grey',
                          command = stop_monitorting)
#where it will be 
start_button.pack(side = 'bottom')    
root.mainloop()   

#traffic monitoring loop
while running:
   
    bytes_received = psutil.net_io_counters().bytes_recv
    bytes_sent = psutil.net_io_counters().bytes_sent
    bytes_total = bytes_received + bytes_sent

    new_receievd = bytes_received - last_received
    new_sent = bytes_sent - last_sent
    new_total = bytes_total - last_total

    mb_new_received = new_receievd / 1024 / 1024
    mb_new_sent = new_sent / 1024 /1024
    mb_new_total = new_total / 1024 / 1024
    
    #we will print it into the txt file so we can log it and open on a GUI
    with open("log.txt", "a") as f:
        print(f"{mb_new_received:.2f} MB received, {mb_new_sent:.2f} MB sent, {mb_new_sent:.2f} MB total", file=f)
    last_received = bytes_received
    last_sent = bytes_sent
    last_total = bytes_total 
    f.close()
    time.sleep(0.5)

According To Python, 2 Loops Can NOT Run Simultaneously!

And There is Already a Loop Running - root.mainloop() (This Means The GUI is Running Continuously, It wont end)

So, As the Rule The Under The Loop - while running: Cant Run!

Now Why Does The while running: Starts When The Window is Closed?

It Starts Because root.mainloop() Is Manually Ended By You So The Code Can Continue to The Other Loop!

Solution:

- Make a Function Where You Would Put Your Code Your want to Run
(I am Not Using Your Code Here, I actually Know Nothing About psutil But Its Not The Case!)

- Put Your Conditionals If You want, else  Put Your Code in The Function

- Now, As in your Case, Run the Function By `FunctionName()` in The `start_monitorting` Function  

My Code:

from tkinter import *

root = Tk()

root.geometry('900x600')
root.configure(bg='black')
def main():
  if running:
    print("For Checking")
    #Your Code  
running = False
a = 1


def start_monitorting():
    global running
    running = True
    main()


def stop_monitorting():
    global running
    running = False

start_button = Button(root, text='Start Monitoring', height=5, width=50, fg='red', bg='grey',
                      command=start_monitorting)
stop_button = Button(root, text='Start Monitoring', height=a, width=50, fg='red', bg='grey',
                     command=stop_monitorting)

start_button.pack(side='bottom')



root.mainloop()

Hope This Helped You!

Basically you have two problems,

1.) #traffic monitoring loop which is the while loop is out of the scope of your Tkinter app or window, So the reason why the loop starts after closing the tkinter window is because the whole Tkinter application is considered as a loop

The code which comes in between the root = Tk() and root.mainloop() is only considered while the app is running. In your case the while loop which is out of the TKinter loop and it can only run when the running loop is completed or terminated. So, that's the reason why the while loop starts after closing the "tkinter window"

2.) If you solved first problem by placing the while loop inside the TKinter loop, there arises the second error: that is condition in while loop didn't validate true because the change of value don't cause while loop to validate again.

To solve the second problem: define the while loop as a function and call where ever you like as other functions.

Solution:

from turtle import color
import time
import psutil
from tkinter import *


root = Tk()             

# Open window having dimension 900x600 and red colour
root.geometry('900x600')
root.configure(bg='black')
# ints for monitoring
last_received = psutil.net_io_counters().bytes_recv
last_sent = psutil.net_io_counters().bytes_sent
last_total = last_received + last_sent
running = False
a=1

#Function for traffic monitoring loop
# -----------------------------------------------
def trafficMonitoringLoop():

  while running:

      # Do your thing 
      # until 'stop_button' is clicked
# -----------------------------------------------

#Define a function to start the programm
def start_monitorting():
    global running
    running = True

    # Calling traffic monitoring loop function
    trafficMonitoringLoop()


def stop_monitorting():
    global running
    running = False

    # Calling traffic monitoring loop function
    trafficMonitoringLoop()


# Create a Button
start_button = Button(root, text = 'Start Monitoring',height=5, width=50, fg='red', bg='grey',
                          command = start_monitorting)
stop_button = Button(root, text = 'Stop Monitoring',height=a, width=50, fg='red', bg='grey',
                          command = stop_monitorting)
#where it will be 
start_button.pack(side = 'bottom')
stop_button.pack(side = 'bottom')


root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM