【发布时间】:2018-10-27 16:31:21
【问题描述】:
我正在尝试使用 PyQt5 构建计算器,我得到了我需要评估的字符串并将其分配给一个变量,以便我可以将该变量作为答案传递给小部件。到目前为止,我可以评估表达式,但不能评估它。我怎样才能做到这一点 ?到目前为止,我有以下代码:-
# this functions gets called when Enter is pressed
def etrp(self):
eqn = self.sender().text() #I get string like '23+4'
eqn1 = "{0} = {1}".format("global x",eqn) #I make it x = 23+4
x = 0
exec(eqn1) # I get error here
print(x)
#some code .....
当我尝试在没有全局的情况下运行它时,它运行时没有错误,但 x 仍然为 0,如果我这样运行它,我会收到以下错误:-
qt5ct: using qt5ct plugin
global x = 12+32
Traceback (most recent call last):
File "/home/orayan/Development/Python/Calculator/calculator.py", line 11, in etrp
exec(eqn1)
File "<string>", line 1
global x = 12+32
^
SyntaxError: invalid syntax
[1] 19185 abort (core dumped) ./main.py
我对python很陌生所以不知道发生了什么
【问题讨论】:
-
1.请向我们展示更多的追溯。 2. 如果您是 Python 新手,请考虑在使用 PyQt5 之前先熟悉该语言。 3. 不要使用全局变量。
-
@Coal_ 1. 我添加了完整的输出 .2。我同意 但是我非常熟悉 C++ 中的 Qt ..
标签: python variable-assignment python-exec