无法将值从条目tkinter导入到另一个.py

时间:2019-02-03 15:08:08

标签: python-3.x tkinter python-module tkinter-entry

我的真实代码通过Excel进行复杂的计算。但是几天前,我被要求提供带有输入参数的图形界面,我在tkinter中编写了一个基本的GUI来将两个值导出到main .PY中,但是我无法导入这些值:c是否有任何解决方案或正确的实现? >

此代码是一个基本示例(有了解决方案,我将开始使其适应我的真实代码)

gui.py

##!/usr/bin/python
import tkinter as tk
import os
from menu import *

def getvalues():
    value1 = float(X.get())
    value2 = float(Y.get())
    return value1, value2

def anotherPY():
    menu.sum1()


root = tk.Tk()
root.geometry("200x200")
root.title("Project")

X = tk.Entry(root)
X.pack()
X.place(relx=.5, rely=.4, anchor="c")

Y = tk.Entry(root)
Y.pack()
Y.place(relx=.5, rely=.6, anchor="c")

b1 = tk.Button(root, text = "Calculate", width = 15, command = anotherPY)
b1.pack()
b1.place(relx=.5, rely=.9, anchor="c")


root.mainloop()

menu.py

from gui import value1, value2

def sum1():
    value3 = value1 + value2
    print(value3)

错误输出为:

C:\Users\Jota\Desktop\Modulos>gui.py
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Jota\Miniconda3\lib\tkinter\__init__.py", line 1705, in 
__call___
    return self.func(*args)
  File "C:\Users\Jota\Desktop\Modulos\gui.py", line 13, in anotherPY
    menu.sum1()
NameError: name 'menu' is not defined
Traceback (most recent call last):
  File "C:\Users\Jota\Desktop\Modulos\gui.py", line 5, in <module>
    from menu import *
  File "C:\Users\Jota\Desktop\Modulos\menu.py", line 1, in <module>
    from gui import value1, value2
ImportError: cannot import name 'value1' from 'gui' 
(C:\Users\Jota\Desktop\Modul
os\gui.py)

感谢阅读的人!

1 个答案:

答案 0 :(得分:0)

为什么不将值作为参数传递

#in gui.py
def anotherPY():
    val1, val2 = getvalues()
    menu.sum1(val1, val2)

并在menu.py中:

def sum1(value1, value2):
    value3 = value1 + value2
    print(value3)

“从gui导入value1,value2”仅导入函数和类,而不是变量