Python tkinter GUI freezing/crashing

2024/11/18 1:49:37
from Tkinter import *
import tkFileDialog
import tkMessageBox
import os
import ttkimport serial
import timeit
import time######################################################################################
class MyApp:def __init__(self, parent):
########################################################
#Setup Framesself.MiddleFrame = Frame(parent) #Middle Frameself.MiddleFrame.pack()#GLOBAL VARIABLESself.chip_number = 0 #number of chip testing
############################################Middle Frame setup  Label(self.MiddleFrame, text='Done').grid(row=8, column=1, sticky = E)self.Done = Canvas(self.MiddleFrame, bg="yellow", width=10, height=10)self.Done.grid(row=8, column=2)         Label(self.MiddleFrame, text='Chip Number:').grid(row=9, column=1, sticky = E)#start buttonself.button1 = Button(self.MiddleFrame,state=NORMAL, command= self.start_pre)self.button1["text"]= "START"self.button1.grid(row=1, column=2, sticky = E)
########################################### 
#Action of Start Buttondef start_pre(self):x = 0while x<10000:         self.start_button()x=x+1#Talking to Boarddef start_button(self):#increase chip count number and updateself.chip_number += 1Label(self.MiddleFrame, text=str(self.chip_number)).grid(row=9, column=2, sticky = E)#reset-yellowself.reset_color()          print "Still Working", self.chip_numberself.Done.configure(background="green")self.Done.update_idletasks()                 ###############################################################
#Color Boxes
#Resetdef reset_color(self):self.Done.configure(background="yellow")self.Done.update_idletasks() 
###############################################################################################################
#Start Programs
root = Tk() #makes window
root.title("Interface")
myapp = MyApp(root) #this really runs program
root.mainloop() #keep window open                                                                           

With my program, i first push the start button. I will print "still working" and the GUi will update chip number and blink done light over and over. The start button go to function that will execute 10000 times. However after 3000 iterations, the gui freeze, but the program is still print "still working". How do I keep the gui from crashing?

Answer

There are many problems with your code. For one, this is fundamentally flawed:

while self.stop == True:         self.start_button()time.sleep(0.5)

You simply can't expect a GUI to behave properly with code like that. As a general rule of thumb you should never have the main thread of a GUI call sleep. Causing sleep prevents the event loop from processing any events, including low level events such as requests to refresh the screen.

The use of sleep has been asked and answered many times on stackoverflow. You might find some of those questions useful. For example,

  • windows thinks tkinter is not responding
  • Python Tkinter coords function not moving canvas objects inside loop
  • How do widgets update in Tkinter?
  • Tkinter multiple operations
  • Python Tkinter Stopwatch Error

You have another problem that falls into the category of a memory leak. From that while loop, you call self.start_button() indefinitely. This happens about once a second, due to sleep being called for half a second in the loop, and another half a second in start_button.

Each time you call start_button, you create another label widget that you stack on top of all previous widgets in row 9, column 2. Eventually this will cause your program to crash. I'm surprised that it causes your program to fail so quickly, but that's beside the point.

My recommendation is to start over with a simple example that does nothing but update a label every second. Get that working so that you understand the basic mechanism. Then, once it's working, you can add in your code that reads from the serial port.

https://en.xdnf.cn/q/118737.html

Related Q&A

If/else in python list comprehension

I would like to return random word from file, based on passed argument. But if the argument doesnt match anythning I dont want to return anything. My method looks like:def word_from_score(self,score):p…

Conditional module importing in Python

Im just trying out Maya 2017 and seen that theyve gone over to PySide2, which is great but all of my tools have import PySide or from PySide import ... in them.The obvious solution would be to find/rep…

AttributeError: list object has no attribute lower : clustering

Im trying to do a clustering. Im doing with pandas and sklearn. import pandas import pprint import pandas as pd from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score from s…

I’m dealing with an error when I run server in Django

PS C:\Users\besho\OneDrive\Desktop\DjangoCrushcourse> python manage.py runserver C:\Users\besho\AppData\Local\Programs\Python\Python312\python.exe: cant open file C:\Users\besho\OneDrive\Desktop\Dja…

python threading with global variables

i encountered a problem when write python threading code, that i wrote some workers threading classes, they all import a global file like sharevar.py, i need a variable like regdevid to keep tracking t…

How to write nth value of list into csv file

i have the following list : sec_min=[37, 01, 37, 02, 37, 03, 37, 04, 37, 05,....]i want to store this list into CVS file in following format: 37,01 37,02 37,03 37,04 ... and so onthis is what i coded: …

Read R function output as columns

Im trying to come up with a way to solve this question I asked yesterday:rpy2 fails to import rgl R packageMy goal is to check if certain packages are installed inside R from within python.Following th…

How does .split() work? - Python

In the following examples, I am splitting an empty string by a space. However, in the first example I explicitly used a space and in the second example, I didnt. My understanding was that .split() and …

How to get email.Header.decode_header to work with non-ASCII characters?

Im borrowing the following code to parse email headers, and additionally to add a header further down the line. Admittedly, I dont fully understand the reason for all the scaffolding around what should…

Elif syntax error in Python

This is my code for a if/elif/else conditional for a text-based adventure game Im working on in Python. The goal of this section is to give the player options on what to do, but it says there is someth…