Python从另一个scrip中的函数导入变量

2024-04-25 17:55:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个项目中,我需要导入变量itemLink从一个文件到另一个。这个变量由一些预定义的字符串和一些必须在GUI中输入的字符串组成。所有的代码都可以工作,但我不知道如何解决这个导入问题。任何帮助都将不胜感激。你知道吗

主程序(GUI)

from tkinter import *
import time
import sys
import subprocess



def generate():
    global itemLink
    itemLink = "predefined_text" + itemName.get() + "predefined_tex" + itemSize.get()
    subprocess.Popen("Nastavitve.py 1", shell=True)

def GUI_start():
    window = Tk()
    window.title("Test")

    Label(window, text="Item name").grid(row=0)
    Label(window, text="Size").grid(row=1)

    global itemName
    global itemSize

    itemName = Entry(window)
    itemSize = Entry(window)

    itemName.grid(row=0, column=1)
    itemSize.grid(row=1, column=1)

    button = Button(window, text="Generate link", fg="red",command=generate)
    button.grid(row=0, column=2)


    window.mainloop()


if __name__ == '__main__':
    GUI_start()

第二个程序(存储必要的数据)

from UI import itemLink
keys = {
    "link": itemLink,
    "email": "your acount email",
    "password": "password"
}

def printLink():
    print(itemLink)
    print("end")

if __name__ == '__main__':
    printLink()

Tags: 字符串textnamefromimportdefguicolumn
2条回答

所以我有两个文件来证明这一点。测试.py,其中itemLink变量驻留并导入_测试.py,以显示导入。你知道吗

这里是测试.py地址:

itemLink = 'no values'
print(itemLink)
def generate():
    itemLink = "predefined_text" #+ itemName.get() + "predefined_tex" + itemSize.get()
    #print(itemLink)

    return itemLink

#we mutate the value of itemLink in the main program
itemLink = generate()

这是进口货_测试.py你知道吗

from test import itemLink
#Now we just have the modified itemLink value without having to import main function to call in the UI program.
print(itemLink)

下面是调用导入的图片_测试.py: enter image description here

我这次在main函数中调用了generate方法来修改itemLink的值,然后将itemLink传递到下一个文件中。你知道吗

如果这是你要找的,告诉我。你知道吗

我刚找到一个解决方案,它可能不是最好的,所以如果有人有任何建议,请写在下面。现在,我必须启动设置,当它导入UI时,它会自动打开UI。单击按钮后,它会按预期在控制台中打印链接。最好我希望它的另一种方式,以便用户界面可以打开设置和存储在那里的变量。你知道吗

设置

from UI import itemName, itemSize

itemLink = "predefined" + itemName.get() + "predefined" + itemSize.get()

print(itemLink)
print("end")

keys = {
    "link": itemLink,
    "email": "your acount email",
    "password": "password"
}

用户界面

from tkinter import *
import time
import sys
import subprocess

def generate():
    #subprocess.Popen("Nastavitve.py 1", shell=True)
    import Settings
    time.sleep(0.1)

window = Tk()
window.title("SHOP BOT")
window.configure(background="black")

Label(window, text="Item name").grid(row=0)
Label(window, text="Size").grid(row=1)

global itemName
global itemSize

itemName = Entry(window)
itemSize = Entry(window)

itemName.grid(row=0, column=1)
itemSize.grid(row=1, column=1)

button = Button(window, text="Generate link", fg="red",command=generate)
button.grid(row=0, column=2)

window.mainloop()

相关问题 更多 >

    热门问题