[英]How to pass user input from one script to another in Python?
I'm creating a GUI application using PyQt5 and am struggling with passing a user input retrieved from a QLineEdit in the first script into the second script. 我正在使用PyQt5创建一个GUI应用程序,并且正在努力将从第一个脚本中的QLineEdit检索到的用户输入传递到第二个脚本中。 The first script is a log-in page and I am trying to pass the username entered in the line edit box into the main application (which is a separate file) as it needs to be displayed in that interface. 第一个脚本是登录页面,我试图将在行编辑框中输入的用户名传递到主应用程序(这是一个单独的文件),因为它需要在该界面中显示。
I have researched this and have only come across methods which pass fixed variables such as 'x = 5' (constants) rather than a user input. 我研究了这个并且只遇到了传递固定变量的方法,例如'x = 5'(常量)而不是用户输入。 How would I go about using a variable that could change at runtime? 我如何使用可能在运行时更改的变量? I have tried the 我试过了
from __main__ import *
method in the called file and I've tried to convert the username variable into a string using 'str(username)' and setting the variable as global but it seems I still get the same error and when the second file is called and it crashes with no error being displayed. 在被调用文件中的方法,我试图使用'str(用户名)'将用户名变量转换为字符串并将变量设置为全局,但似乎我仍然得到相同的错误,当第二个文件被调用时它崩溃了没有显示错误。 Here is the relevant code taken from different areas of the script: 以下是从脚本的不同区域获取的相关代码:
file1.py file1.py
import os
global username
username = self.lineEdit_username.text()
username = str(username)
import file2
MainWindow.close()
os.system('file2.py')
file2.py file2.py
from __main__ import *
print(username) # just to check if the variable has been imported
I've tried researching this as much as I can before posting this but if I have missed a solution somwhere else please point me in the right direction. 我已经尝试过尽可能多地研究这个,但是如果我错过了其他地方的解决方案,请指出我正确的方向。
Thanks for the help 谢谢您的帮助
The easiest way I have done this, especially with PyQt, is utilizing classes and importing the file as a module. 我这样做的最简单的方法,特别是使用PyQt,就是利用类并将文件作为模块导入。 See the example below. 请参阅下面的示例。
Pass_variable.py: 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: retrieve_variable.py:
from Pass_variable import user_input
x = user_input()
x.get_input()
print(x.entry)
so you are basically importing the class user_input
from the file Pass_variable
, assigning x
to the class and then anything that is under self
is now stored in the x
variable. 因此,您基本上从文件Pass_variable
导入类user_input
,将x
分配给类,然后在self
下的任何内容现在都存储在x
变量中。 So x.entry
is the same thing as calling self.entry
inside the pass_variable.py file. 所以x.entry
与在pass_variable.py文件中调用self.entry
是一回事。
Does this make sense? 这有意义吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.