python - 有没有办法让 tkinter 在相互添加两个变量时显示不同的标签
问题描述
我刚开始学习python,我正在尝试做一个基本的计算器类的东西,当你将两个元素加在一起时显示它是什么化合物,我希望这个代码在我输入氧气+氧气时显示“O2”作为标签或“ H2”当我进入氢气+氢气等。但它现在显示“OO”和“HH”等。有没有办法做我想做的事?这是我当前的代码:
carbon = "C"
oxygen = "O"
hydrogen = "H"
root = Tk()
e = Entry(root, width = 50)
e.pack()
def myClick():
myLabel = Label(root, text =eval(e.get()))
myLabel.pack()
myButton = Button(root, text="Calculate", command = myClick)
myButton.pack()
root.mainloop()
解决方案
我假设您希望用户输入类似oxygen + oxygen
. 当使用 评估该表达式时eval(e.get())
,两个字符串(在本例中为"O"
和"O"
)被连接起来,这基本上意味着一个被卡在另一个之后(就像两个乐高积木一样)。字符串的值不会以任何方式在数学上相加。您要做的是创建一个新变量,然后将其拆分为“+”号并比较结果。myClick()
我写了一些代码来更好地解释这一点(除了函数之外,一切都是一样的:
from tkinter import *
carbon = "C"
oxygen = "O"
hydrogen = "H"
root = Tk()
e = Entry(root, width = 50)
e.pack()
def myClick():
# This is the new section
temp = e.get().split(sep='+') # this will return a list containing
mystr = "" # empty string
temp = [i.strip() for i in temp] # this will get rid of any space characters (.strip()) below and after the strings
# if you want to remove specific characters, use .strip(chars=mylist)
# include those characters in mylist
if temp[0] == temp[1]:
mystr = eval(temp[0]) + "2" # when both strings are the same
elif temp[0] != temp[1]: # you could also use a plain 'else:' statement here
mystr = eval(temp[0]) + eval(temp[1]) # when strings are different
myLabel = Label(root, text=mystr)
myLabel.pack()
myButton = Button(root, text="Calculate", command = myClick)
myButton.pack()
root.mainloop()
推荐阅读
- python - 为独立条目填充 NumPy 数组的有效方法?
- excel - Excel VBA - 每个唯一组的 N 个随机记录
- postgresql - 如何编写 PostgreSQL 存储过程来查找和终止空闲查询?
- javascript - 使用 chart.js 的实时滚动图表
- c# - 在 .NET 5 WinForms 应用程序中使用非托管 32/64 位 DLL
- vue.js - 如何在 Vue.js 中创建弹出按钮?
- odoo - 错误:无法读取未定义的属性(读取“道具”)
- flutter - Keycloak 给了我 XMLHttpRequest 错误。有颤振但不要有邮递员
- salesforce - 创建一个转换列表的方法
到地图 以 SObjectField 作为方法参数,有什么建议吗? - next.js - 基于主机的路由