How do I pass a value to another file, which is itself imported in current file?

╄→尐↘猪︶ㄣ 提交于 2020-01-07 03:22:13

问题


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:

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

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

File.py:

from tkinter import *
import tkinter_file

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

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'

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?


回答1:


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!

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()))


来源:https://stackoverflow.com/questions/42607002/how-do-i-pass-a-value-to-another-file-which-is-itself-imported-in-current-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!