【问题标题】:Infinite Loop Issue - Intersections无限循环问题 - 交叉点
【发布时间】:2021-08-03 22:03:15
【问题描述】:

我尝试了一个系统,希望能防止线路交叉。然而,当它运行时,它创建了一个似乎是无限循环的东西。我不确定问题是什么。这是代码。

#detecting the overlap
intersection1 = Line1.intersection(Line1)

while Line1 == intersection1:
    importlib.reload(tkinter)
    print('failed attempt')
    continue

    while Line1 != intersection1:
        print('successful attempt')
        break 

为了运行程序,需要完整的代码,我将在下面列出,但上面是有问题的部分。

#imports
import tkinter
from tkinter import * 
import random
from random import randint
import math
import time

import pip 
import shapely
from shapely.geometry import LineString
import importlib

#setting up the canvas
master = Tk()
master.geometry("500x500")
master.title("Sprouts")

w = Canvas(master, width=500, height=500, bg="white")
w.pack()

#creating the circle
def create_circle(x, y, r, w): #center coordinates, radius
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return w.create_oval(x0, y0, x1, y1)

#creating coordinate variables
xC = random.randint(10,490)
yC = random.randint(10,490)
xC2 = random.randint(10,490)
yC2 = random.randint(10,490)

L1C1 = random.randint(10,490)
L1C2 = random.randint(10,490)
L1C3 = random.randint(10,490)
L1C4 = random.randint(10,490)

#displaying the circle
c1 = create_circle(xC, yC, 5, w)
c2 = create_circle(xC2, yC2, 5, w)

#displaying the line #implementing the curve
Line1 = LineString([(xC, yC), (xC2, yC2)]
              or [(xC, yC), (L1C1, L1C2), (xC2, yC2)]
              or [(xC,yC), (L1C1, L1C2), (L1C3, L1C4), (xC2, yC2)])

Line1show = w.create_line(xC, yC, xC2, yC2 or
                          xC, yC, L1C1, L1C2, xC2, yC2 or
                          xC, yC, L1C1, L1C2, L1C3, L1C4, xC2, yC2,
                          smooth='1',width="2")

#detecting the overlap
intersection1 = Line1.intersection(Line1)

while Line1 == intersection1:
    importlib.reload(tkinter)
    print('failed attempt')
    continue

    while Line1 != intersection1:
        print('sucessful attempt')
        break 
                 
w.mainloop()

【问题讨论】:

    标签: python tkinter line infinite-loop overlap


    【解决方案1】:

    问题在于continue 的使用,它会让你一直回到循环的开头

    这是一个简单的说明性示例,与有问题的代码部分相同

    >>> msj=""
    >>> while msj!="yes":
            print("msj is not 'yes'")
            continue
            msj=input("write msj")
    
    
    msj is not 'yes'
    msj is not 'yes'
    msj is not 'yes'
    ...
    

    在这里你永远不会到达msj=input("write msj"),因为continue 返回到循环的开头,而前一部分没有改变循环的条件,因此你以无限循环结束......

    continue 更正确的用法是使用条件语句 if 来跳过不需要处理的事情,例如在伪代码中这样的事情:

    while dowork:
        if not condition(data):
            continue
        result=work_on_data(data)
        if check_if_done(result):
            break
        data=get_next_data()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 2021-09-02
      • 2020-09-09
      • 2021-09-11
      相关资源
      最近更新 更多