Search code examples
pythontkintertkinter-canvastraveling-salesman

Drawing and Clearing several lines in Tkinter


So I'm working on developing a genetic algorithm for Traveling Salesman Problem in Python currently using Tkinter to display my results. The algorithm is going well, but I need to figure out some issues with displaying the results.

Basically, I have it generate a random set of points and display them in the window, then when I have it run the solution, it creates lines connecting all the points in the best order it finds in a single set (or "generation") of orders. From there, it should have the option to generate the next generation which will clear all current lines, leaving the points visible, then draw new lines based on the next generation's best solution. Currently, however I'm having trouble determining the best way to clear the lines without clearing the points.

This is the code I'm using to generate the lines:

    for i in range(0, numCities-1):
        x1 = points[bestOrder[i]][0]
        y1 = points[bestOrder[i]][1]
        x2 = points[bestOrder[i+1]][0]
        y2 = points[bestOrder[i+1]][1]
        w.create_line(x1, y1, x2, y2)

In this example, 'w' represents my canvas and 'numCities' is a value assigned in the window to determine how many points to create. I plan to tie the clearing of the lines to a function that will be called when a button is pressed.

Any suggestions for the best way to achieve what I'm trying to do here? Even if it requires restructuring how I've got the line generating working, I'm up for anything.


Solution

  • Not sure if this is what you want, you have not shown enough code. Add the lines to a list then you can delete the items in the list at another time.

    lines = []
    for i in range(0, numCities - 1):
        x1 = points[bestOrder[i]][0]
        y1 = points[bestOrder[i]][1]
        x2 = points[bestOrder[i + 1]][0]
        y2 = points[bestOrder[i + 1]][1]
        lines.append(w.create_line(x1, y1, x2, y2))
    
    
    for line in lines:
        w.delete(line)