首页 > 解决方案 > 有没有办法让 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()

标签: pythontkinter

解决方案


我假设您希望用户输入类似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()

推荐阅读