繁体   English   中英

如何在Python中将用户输入从一个脚本传递到另一个脚本?

[英]How to pass user input from one script to another in Python?

我正在使用PyQt5创建一个GUI应用程序,并且正在努力将从第一个脚本中的QLineEdit检索到的用户输入传递到第二个脚本中。 第一个脚本是登录页面,我试图将在行编辑框中输入的用户名传递到主应用程序(这是一个单独的文件),因为它需要在该界面中显示。

我研究了这个并且只遇到了传递固定变量的方法,例如'x = 5'(常量)而不是用户输入。 我如何使用可能在运行时更改的变量? 我试过了

from __main__ import *

在被调用文件中的方法,我试图使用'str(用户名)'将用户名变量转换为字符串并将变量设置为全局,但似乎我仍然得到相同的错误,当第二个文件被调用时它崩溃了没有显示错误。 以下是从脚本的不同区域获取的相关代码:

file1.py

import os

global username
username = self.lineEdit_username.text()
username = str(username)
import file2
MainWindow.close() 
os.system('file2.py') 

file2.py

from __main__ import *
print(username)  # just to check if the variable has been imported

我已经尝试过尽可能多地研究这个,但是如果我错过了其他地方的解决方案,请指出我正确的方向。

谢谢您的帮助

我这样做的最简单的方法,特别是使用PyQt,就是利用类并将文件作为模块导入。 请参阅下面的示例。

Pass_variable.py:

import tkinter as tk
class user_input(object):
    def get_input(self):
        def get_text():
            self.entry = user_entry.get()
            print(self.entry)
            root.destroy()

        root = tk.Tk()

        root.title('Name')

        user_entry = tk.Entry(root)
        user_entry.pack()
        user_entry.focus_set()

        okay_button = tk.Button(root,text='okay',command=get_text)
        okay_button.pack(side='bottom')
        root.mainloop()

retrieve_variable.py:

from Pass_variable import user_input

x = user_input()
x.get_input()
print(x.entry)

因此,您基本上从文件Pass_variable导入类user_input ,将x分配给类,然后在self下的任何内容现在都存储在x变量中。 所以x.entry与在pass_variable.py文件中调用self.entry是一回事。

这有意义吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM