0

Вот программа, разбитая на два модуля. Когда я импортирую первый модуль во второй, то выскакивает ошибка тем, что имя "Click" не объявлено. Не понимаю в чем проблема.

модуль calc_func

from tkinter import *
from decimal import *

activeStr = ' '
Stack = []

def Calculate():
   global stack
   global label
   result = 0
   num2 = Decimal(Stack.pop())
   operation = Stack.pop()
   num1 = Decimal(Stack.pop())

   if operation == '+':
       result = num1 + num2
   if operation == '-':
       result = num1 - num2
   if operation == '/':
     try:
       result = num1 / num2
     except DivisionByZero:
          result = "На 0 делить нельзя!"
   if operation == '*':
       result = num1 * num2
   label.configure(text = str(result))


def Click(text):
     global activeStr
     global Stack

     if text == 'CE':
          Stack.clear()
          activeStr = ' '
          label.configure(text = '0')

     elif '0' <= text <= '9':
          activeStr += text
          label.configure(text = activeStr)

     elif text == '.':
          if activeStr.find('.') == -1:
               activeStr += text
               label.configure(text = activeStr)

     else:
          if len(Stack) >= 2:
               Stack.append(label['text'])
               Calculate()
               Stack.clear()
               Stack.append(label['text'])
               activeStr = ' '
               if text != '=':
                    Stack.append(text)
          else:
               if text != '=':
                    Stack.append(label['text'])
                    Stack.append(text)
                    activeStr = ' '
                    label.configure(text = '0')

модуль RGZ

from tkinter import *
from decimal import *
import calc_func

win = Tk()
win.title('Калькулятор')

buttons = (('7', '8', '9', '/'),
          ('4', '5', '6', '*'),
          ('1', '2', '3', '-'),
          ('0', '.', '=', '+')
          )


label = Label(win, text = '0', width = 35, font = 'Times 15')
label.grid(row = 0, column = 0, columnspan = 4, sticky = "nsew")

button = Button(win, text = 'CE', font = 'Times 15', command = lambda text = 'CE': Click(text))
button.grid(row = 1, column = 3, sticky = "nsew", ipadx = 20, ipady = 5)
for row in range(4):
   for col in range(4):
       button = Button(win, text = buttons[row][col], font = 'Times 15', command = lambda row = row, col = col: Click(buttons[row][col]))
       button.grid(row = row + 2, column = col, sticky = "nsew", ipadx = 30, ipady = 15)

win.grid_rowconfigure(6, weight = 1)
win.grid_columnconfigure(4, weight = 1)

win.mainloop()
1
  • Кстати, лучше называть функции в snake_case. Принято, что название в UpperCamelCase обозначает класс.
    – nomnoms12
    17 мая 2020 в 12:46

2 ответа 2

0

В Вашем модуле нет функции Click — она в импортируемом.

Обращайтесь через него:

calc_func.Click

Или импортируйте в текущую область видимости с помощью from:

from calc_func import Click
0

я отметил для вас строки, в которые внес изменения.

RGZ.py

from tkinter import *
from decimal import *

#import calc_func
from calc_func import Click                                                          # Click

win = Tk()
win.title('Калькулятор')

buttons = (('7', '8', '9', '/'),
          ('4', '5', '6', '*'),
          ('1', '2', '3', '-'),
          ('0', '.', '=', '+')
          )


label = Label(win, text = '0', width = 35, font = 'Times 15')
label.grid(row = 0, column = 0, columnspan = 4, sticky = "nsew")

button = Button(win, 
                text = 'CE', 
                font = 'Times 15', 
                command = lambda text='CE', label=label: Click(text, label))               # label
button.grid(row = 1, column = 3, sticky = "nsew", ipadx = 20, ipady = 5)
for row in range(4):
   for col in range(4):
       button = Button(win, 
                       text = buttons[row][col], 
                       font = 'Times 15', 
                       command = lambda row=row, col=col: Click(buttons[row][col], label)  # label
                      )
       button.grid(row = row + 2, column = col, sticky = "nsew", ipadx = 30, ipady = 15)

win.grid_rowconfigure(6, weight = 1)
win.grid_columnconfigure(4, weight = 1)

win.mainloop()

calc_func.py

from tkinter import *
from decimal import *

activeStr = ' '
Stack = []

def Calculate(label):                                           # label
   global stack
#   global label
   result = 0
   num2 = Decimal(Stack.pop())
   operation = Stack.pop()
   num1 = Decimal(Stack.pop())

   if operation == '+':
       result = num1 + num2
   if operation == '-':
       result = num1 - num2
   if operation == '/':
     try:
       result = num1 / num2
     except DivisionByZero:
          result = "На 0 делить нельзя!"
   if operation == '*':
       result = num1 * num2
   label.configure(text = str(result))


def Click(text, label):                                              # label
     global activeStr
     global Stack

     if text == 'CE':
          Stack.clear()
          activeStr = ' '
          label.configure(text = '0')

     elif '0' <= text <= '9':
          activeStr += text
          label.configure(text = activeStr)

     elif text == '.':
          if activeStr.find('.') == -1:
               activeStr += text
               label.configure(text = activeStr)

     else:
          if len(Stack) >= 2:
               Stack.append(label['text'])
               Calculate(label)                                        # label
               Stack.clear()
               Stack.append(label['text'])
               activeStr = ' '
               if text != '=':
                    Stack.append(text)
          else:
               if text != '=':
                    Stack.append(label['text'])
                    Stack.append(text)
                    activeStr = ' '
                    label.configure(text = '0')

введите сюда описание изображения

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.