Импорт функций, классов и переменных в другие модули python 3.7? - PullRequest
0 голосов
/ 03 июня 2019

Я создаю программу, которая визуализирует различные алгоритмы сортировки.В одном модуле у меня есть класс под названием Algorithms, в котором все мои алгоритмы сортировки и поиска хранятся в виде собственных методов, а у меня есть другой модуль с именем main, который содержит другие вещи, такие как переменные и функции, связанные с программой.Основная проблема заключается в том, что мне нужно импортировать класс алгоритма в основной модуль, а переменную и функцию в модули алгоритмов.Но я получаю ImprotError

Основной модуль

from algorithms import Algorithm
from tkinter import *
import random
import time

a_list = [] # values of the list I want to sort, starts empty
bar_coords = [] # list of lists of coordinates for each of the bars represented in the canvas
list_of_numbers = [] # to be used by the algorithm class

def initialize_list_elements(num_of_elements, up_to):
    global list_of_numbers
    clear_lists()
    for _ in range(num_of_elements):
        list_of_numbers.append(random.randint(1, up_to))
    return list_of_numbers

def random_colour_code():
    hex_chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
    colour_code = '#'
    for i in range(0,6):
        colour_code = colour_code + choice(hex_chars)
    return colour_code

def clear_lists():
    global a_list
    global list_of_numbers
    list_of_numbers.clear()
    a_list.clear()
    canvas.delete('all')

def number_list():
    global list_of_numbers
    return list_of_numbers

def draw():
    x = 0
    global a_list
    a_list = initialize_list_elements(30, 600) # same as the
    for value in a_list: # so for each value in our list of values
        x = x + 30 # each
        y = 700 - int(value) # assign a point y
        bars = canvas.create_line((x, 700, x, y), width = 10, fill='black') # then we draw a line using the points (x, 200) and (x, y)
        canvas.create_text(x, y-10, text=str(value))
        bar_coords = canvas.coords(bars)

algorithm_list = ['Binary Search', 'Jump Search', 'Linear Search', 'Bubble Sort', 'Heap Sort', 'Insertion Sort', 'Merge Sort', 'Quick Sort', 'Selection Sort']

window = Tk()
window.title('Algorithm Testbed')
title_frame = Frame(window) # a frame used to display the title of the program
button_frame = Frame(window) # a frame to hold the buttons
canvas_frame = Frame(window) # a frame for the canvas

var = StringVar(button_frame)
var.set(algorithm_list[0])

canvas = Canvas(canvas_frame, width=910, height=700, background='white')

title_label = Label(title_frame, text='Searching & Sorting Algorithm Testbed', font='Helvetica 20 bold')

init_button = Button(button_frame, text='     Initialise     ', width=15, pady=10, command=draw)
start_button = Button(button_frame, text='     Start     ', width=15, pady=10)
pause_button = Button(button_frame, text='     Pause     ', width=15, pady=10)
step_button = Button(button_frame, text='     Step     ', width=15, pady=10)
clear_button = Button(button_frame, text='     Clear     ', width=15, pady=10, command=clear_lists)
drop_down_menu = OptionMenu(button_frame, var, *algorithm_list)

# putting the label onto the title_frame
title_label.grid(rowspan=2, column=0)
# putting buttons onto the button_frame
init_button.grid(rowspan=1, column=0, pady=10, padx=5)
start_button.grid(rowspan=1, column=0, pady=10, padx=5)
pause_button.grid(row=2, column=0, pady=10, padx=5)
step_button.grid(row=3, column=0, pady=10, padx=5)
clear_button.grid(row=4, column=0, pady=10, padx=5)
drop_down_menu.grid(row=5, column=0, pady=10, padx=5)
# putting canvas onto canvas_frame
canvas.grid(row=0, column=0)

# putting frames on the window
title_frame.grid(row=0, columnspan=2)
button_frame.grid(row=1, column=0)
canvas_frame.grid(row=1, column=1)
window.mainloop()

Модуль алгоритмов (будет слишком длинным, чтобы включить его, поэтому просто сокращенную версию

from main import number_list
from main import canvas

# file contains all the algorithms to be animated.
class Algorithm:
    def sort_list(self, list): # Uses library function to sort list
        list.sort()
        return list

свыше и из операторов import Я получаю сообщение об ошибке: ImportError: невозможно импортировать имя 'number_list' из 'main' (C: \ Users \ Kirome \ Documents \ GitHub \gorithm-animation-python \ main.py) Я получаю ту же ошибкудля импорта в модуле алгоритмов и в главном модуле я получаю ту же ошибку для оператора from algorithms import Algorithm

Если у меня есть только один из оператора from / import в одном из модулей, он будет работать, который яне понимаю, что происходит.

...