我有一个文本文件,使用以下行为参数指定数值:
designPoint1.SetParameterExpression(Parameter=parameter1, Expression="50")
我想创建一个GUI,用户可以在其中为参数指定新值(例如20)。此GUI必须替换上一行中的新值,以便替换结果为:
designPoint1.SetParameterExpression(Parameter=parameter1, Expression="20")
这是我试图做的事情:
import sys
from tkinter import *
def NewValues():
diamValue = Diameter.get()
cpValue = Cp.get()
cbValue = Cb.get()
gammaValue = GammaRel.get()
epsValue = Epsilon.get()
with open('parametri.txt', 'r') as input_file, open('newparametri.txt', 'w') as output_file:
for line in input_file:
if line.strip() == 'designPoint1.SetParameterExpression(Parameter=parameter1, Expression="50")':
output_file.write('designPoint1.SetParameterExpression(Parameter=parameter1, Expression="diamValue"\n)')
else:
output_file.write(line)
return
def RunSimulation():
pass
return
App = Tk()
Diameter = StringVar()
Cp = StringVar()
Cb = StringVar()
GammaRel = StringVar()
Epsilon = StringVar()
App.geometry("250x200")
App.title("Static Calculator")
AppLabel1 = Label(text="Diameter").grid(row =0,column =0,sticky="W")
AppLabel2 = Label(text="Cp").grid(row=1,column=0,sticky="W")
AppLabel3 = Label(text="Cb").grid(row=2,column=0,sticky="W")
AppLabel4 = Label(text="Gamma Rel").grid(row=3,column=0,sticky="W")
AppLabel5 = Label(text="epsilon").grid(row=4,column=0,sticky="W")
AppEntry1 = Entry(App,textvariable=Diameter).grid(row =0,column =1)
AppEntry2 = Entry(App,textvariable=Cp).grid(row =1,column =1)
AppEntry3 = Entry(App,textvariable=Cb).grid(row =2,column =1)
AppEntry4 = Entry(App,textvariable=GammaRel).grid(row =3,column =1)
AppEntry5 = Entry(App,textvariable=Epsilon).grid(row =4,column =1)
Appbutton1 = Button(App,text = "Update Values",command = NewValues,).grid(row =5,column =1)
Appbutton2 = Button(App,text = "Run",command = RunSimulation,).grid(row =6,column =1)
App.mainloop()
显然,此代码的结果是:
designPoint1.SetParameterExpression(Parameter=parameter1, Expression="diamValue")
是否可以更正此代码以达到目标?
感谢您的帮助。
答案 0 :(得分:1)
output_file.write('designPoint1.SetParameterExpression(Parameter=parameter1, Expression="diamValue"\n)')
您的错误就在这一行。你需要连接/格式化你的字符串。
使用连接,
myVariable = "world"
print("Hello "+myVariable+"!")
使用.format()
,
myVariable = "world"
print("Hello {var}!".format(var=myVariable))
关于字符串格式,您还应该检查这个问题 Pythons many ways of string formatting — are the older ones (going to be) deprecated?
答案 1 :(得分:0)
根据Lafexlos的例子而不是:
output_file.write('designPoint1.SetParameterExpression(Parameter=parameter1, Expression="diamValue"\n)')
你应该连接变量和字符串,如下所示:
output_file.write('designPoint1.SetParameterExpression(Parameter=parameter1, Expression="'+ diamValue +'"\n)')
或使用.format()方法
output_file.write('designPoint1.SetParameterExpression(Parameter=parameter1, Expression="{0}"\n)'.format(diamValue))
您可能需要使用第一个示例将变量格式化为字符串:str(variablename)