如何将值传递给另一个文件,该文件本身是在当前文件中导入的? [英] How do I pass a value to another file, which is itself imported in current file?

查看:17
本文介绍了如何将值传递给另一个文件,该文件本身是在当前文件中导入的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件,一个包含 tkinter 代码,另一个包含一个函数.我在 tkinter 窗口中有一个按钮和一个 Entry 字段.我试图在单击按钮时执行该功能,但它需要 Entry 字段中的文本才能工作.尝试从 tkinter 文件导入任何内容时出现错误:

I have two files, one containing the tkinter code and another containing a function. I have a button in the tkinter window and an Entry field. I am trying to execute the function when clicking the button, but it needs the text from the Entry field to work. I get an error when trying to import anything from the tkinter file:

tkinter_file.py:

tkinter_file.py:

import File
window = Tk()
def input():
    s = entry1.get()
    return s

entry1 = Entry(window)
button1 = Button(window, text='GO', command=File.function)

文件.py:

from tkinter import *
import tkinter_file

def function():
    req_url = 'http://someurl.com/{}'.format(tkinter_file.input)
    requests get url etc. etc.

我似乎在将 tkinter_file 导入 File.py 或什至只是函数 input 时收到错误:

I seem to be getting an error as soon as I import the tkinter_file into File.py, or even just the function input:

File "/etc/etc/tkinter_file.py", line 75, in <module>
button1 = Button(window, text='GO', command=File.function)
AttributeError: module 'File' has no attribute 'function'

我认为 req_url 没有立即获得 s 值是问题所在,也可能将这两个文件相互导入,但是你怎么做克服这个?

I'm thinking that req_url not having the value s straight away is the problem, as well as maybe importing the 2 files into each other, but how do you overcome this?

推荐答案

如果你有两个模块,比如 a.pyb.py,你不能在 a 中导入模块 b,然后在 b 中导入模块 a,因为这会创建一个 循环 依赖,无法明确解决!

If you have two modules, say a.py and b.py, you can't import module b in a and then import module a in b, because that creates a cyclic dependency, which can't clearly be solved!

一个解决方案是将函数作为参数传递给 File.function 使该函数正常运行所需的内容,即 entry1 的内容.

A solution would be to pass as parameter to File.function what you need for that function to run properly, i.e. the contents of the entry1.

button1 = Button(window, text='GO', command=lambda: File.function(entry1.get()))

这篇关于如何将值传递给另一个文件,该文件本身是在当前文件中导入的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆