繁体   English   中英

如何用数字乘/除输入框,tkinter

[英]How To Multiply / Divide Entry Box With A Number, tkinter

嘿,我对 python 很陌生,我在高中学习 class。 对于我正在处理的任务,我们必须制作一个 tkinter gui,其中包括小部件、label、按钮、输入框、单选或复选按钮、框架和显示框。 我正在制作公里到英里的转换器,如果选择它可以做相反的事情,用户可以选择单选按钮来选择他们想要计算的那个,但是我在计算部分遇到了很多麻烦,因为我无法将输入框编号乘以或除以 1.609 或任何数字。 这是我现在拥有的代码,我为混乱以及它可能有多糟糕表示歉意

import tkinter as tk
import tkinter.messagebox

# Customize main window
root = tk.Tk()
root.title('GUI Assignment')



# Create the frames, right, left, and bottom, and pack them
bframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
bframe.pack(side='bottom')
rframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
rframe.pack(side='right')
lframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
lframe.pack(side='left')


# Make the label and the entry box for the right frame
dlabel = tk.Label(rframe, text = 'Enter the distance', )
dentry = tk.Entry(rframe, width=75)
# Pack the label and entry
dlabel.pack(side='left')
dentry.pack(side="right")
dist = 3.0
temp =(dentry.get())
# Create the convert command
def convert():
    if radio_var.get()==1:
        tkinter.messagebox.showinfo('Distance',temp / dist )

# Make the convert and quit buttons
b = tk.Button(bframe, text="Convert", command=convert)
quit = tk.Button(bframe, text='Quit', command=root.destroy)

# Pack the buttons
b.pack(side='left')
quit.pack(side='right')

# Make the radio variable 
radio_var = tk.IntVar()
radio_var.set(1)

# Make the radio buttons for the left frame
rb = tk.Radiobutton(lframe, text='Km to Miles', variable=radio_var, value=1)
rb2 = tk.Radiobutton(lframe, text='Miles to Km', variable=radio_var, value=2)

# Pack The Radio Buttons
rb.pack()
rb2.pack()

    

root.mainloop()

您在这里遇到的问题是您试图将temp字符串除以dist浮点数。 在使用float(temp)进行转换之前,您需要将temp转换为 float。 此外,由于您在脚本期间设置了一次temp ,因此它只会在分配变量后立即引用输入框中的值。 为了解决这个问题,你必须在你的convert() function 内部而不是在它外部调用dentry.get()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM