我对 python 和 tkinter 非常陌生,我正在尝试制作一个非常简单和基本的计算器。
此代码按我的预期工作,只是如果我想在不重新启动程序的情况下打印 2 个结果,则标签会重叠。
这就是我打印 50 * 50 然后将其更改为 50/50 而不重新启动程序时的样子。
from tkinter import *
w = Tk()
#****FUNCTIONS****
def multiply():
number1 = float(e1.get())
number2 = float(e2.get())
result1 = number1 * number2
resultlabel1 = Label(w, text=result1)
resultlabel1.grid(row=2, column=0)
def division():
number1 = float(e1.get())
number2 = float(e2.get())
result1 = number1 / number2
resultlabel1 = Label(w, text=result1)
resultlabel1.grid(row=2, column=0)
def addition():
number1 = float(e1.get())
number2 = float(e2.get())
result1 = number1 + number2
resultlabel1 = Label(w, text=result1)
resultlabel1.grid(row=2, column=0)
def subtraction():
number1 = float(e1.get())
number2 = float(e2.get())
result1 = number1 - number2
resultlabel1 = Label(w, text=result1)
resultlabel1.grid(row=2, column=0)
# ****LABELS, ENTRIES AND BUTTONS****
l1 = Label(w, text="First number: ")
l2 = Label(w, text="Second number: ")
e1 = Entry(w)
e2 = Entry(w)
b1 = Button(w, text="*", command=multiply)
b2 = Button(w, text="/", command=division)
b3 = Button(w, text="-", command=subtraction)
b4 = Button(w, text="+", command=addition)
b5 = Button(w, text="Exit", command=w.quit)
#****PLACEMENTS****
l1.grid(row=0, column=0)
l2.grid(row=1, column=0)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
b1.grid(row=0, column=2)
b2.grid(row=0, column=3)
b3.grid(row=1, column=3)
b4.grid(row=1, column=2)
b5.grid(row=2, column=4)
w.mainloop()
最佳答案
在创建 GUI 其余部分的函数之外定义 resultlabel1
。然后添加
resultlabel1.config(text=result1)
改为所有函数 - 即使标签是在它们下面定义的,它也会起作用,因为它现在是一个全局变量。这将不需要每次都创建一个新标签,而只需更改一个标签中显示的文本,从而防止任何重叠。
关于python - Tkinter 标签重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53898526/