tkinter输出无显示
我知道这个函数在按钮上是有效的,它确实能获取到数字,我也可以打印出Num
这个变量。但是当我把它设置为输出字符串时,似乎在输出文本中没有显示出来。我猜我在使用output_str.set函数或者textvariable
函数时可能做错了什么,但我就是搞不清楚到底是什么问题。
顺便说一下,没有抛出任何错误。
import tkinter as tk
def clicked():
num = (entry_int.get())
Num = num * 0.45
output_str.set = (Num)
window = tk.Tk()
window.title("Pounds to kilos")
window.geometry('350x200')
title = tk.Label(window, text = "Pounds to Kg", font = "helvectica" )
title.place(x = 115)
entry_int = tk.IntVar()
txt = tk.Entry(window, width = 15, textvariable = entry_int)
txt.place(x= 129, y= 30)
output_str = tk.StringVar()
output = tk.Label(window, fg = "blue", textvariable = output_str, font = "helvectic")
output.place(x= 126, y= 50)
btn = tk.Button(window, text = "Calculate",fg = "red", command = clicked )
btn.place(x = 240, y = 26)
window.mainloop()
我测试了输出文本,确认它确实能获取到输入的数字。
我希望Num
这个变量能在输出标签中显示出来。
1 个回答
0
使用tkinter时,输出没有任何显示
- 你不能直接在
Label
这个控件里设置StringVar()
。 - 调整一下
y
轴的坐标,这样我们就能看到Label
的输出。因为它被遮住了。 - 在
Label
的输出中,添加.configure
来更新clicked()
的内容。 - 在
clicked()
中为输入框添加浮点数。
就这些。你准备好开始了。
代码片段:
import tkinter as tk
def clicked():
num = float(entry_int.get())
Num = num * 0.45
print(Num)
output.configure(text=Num)
window = tk.Tk()
window.title("Pounds to kilos")
window.geometry('350x200')
title = tk.Label(window, text = "Pounds to Kg", font = "helvectica" )
title.place(x = 115)
entry_int = tk.IntVar()
txt = tk.Entry(window, width = 15, textvariable = entry_int)
txt.place(x= 129, y= 30)
#output_str = tk.StringVar()
output = tk.Label(window, width= 20, bg = "white", font = "helvectic")
output.place(x= 126, y= 60)
btn = tk.Button(window, text = "Calculate",fg = "red", command = clicked )
btn.place(x = 240, y = 26)
window.mainloop()
截图: