为下拉选择分配不同的值

Assign a different value to a drop down selection

我的计算程序有一个下拉菜单,其中有 7 个选项。我想为每个选择分配一个不同的值,以便当用户进行选择时,备用值将传递给进行计算的公式。例如,如果用户选择 42,替代值将是 2143,它将传递到我公式的 ohms = float(e4.get()) 部分。我该怎么做?我正在使用 PyCharm.

from tkinter import *
import os
os.system('clear')

root = Tk()
root.title('Pickup Coil Turn Count Calculator')
root.geometry("400x700")
root.configure(bg='#ffc773')


#turn_count holds the math formula for the calculation
def turn_count():
    width, length, ohms, resistance = float(e2.get()), float(e3.get()), float(e4.get()), float(e5.get())
    turn_count = resistance / ohms * 1000 * 12 / ((width * 3.14) + length + length - width * .19) * .969
    count_label['text'] = int(turn_count)

#for the reset button
def clear_fields():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e3.delete(0, 'end')
    clicked.set(options[0])
    e5.delete(0, 'end')
    count_label.config(text='')


myLabel = Label(root, text='Enter Core Height', bg='#ffc773')
myLabel.pack(pady=10)
e1 = Entry(root, width=10, justify='center', border=0)
e1.pack()

myLabel = Label(root, text='Enter Core Width', bg='#ffc773')
myLabel.pack(pady=10)
e2 = Entry(root, width=10, justify='center', border=0)
e2.pack()

myLabel = Label(root, text='Enter Core Length', bg='#ffc773')
myLabel.pack(pady=10)
e3 = Entry(root, width=10, justify='center', border=0)
e3.pack()

myLabel = Label(root, text='Select Wire Gauge', bg='#ffc773')
myLabel.pack(pady=10)

#each option would have an alternate value
options = [
    '38',
    '39',
    '40',
    '41',
    '42',
    '43',
    '44',
]

clicked = IntVar()
clicked.set(options[0])

drop = OptionMenu(root, clicked, *options)
drop.pack()

myLabel = Label(root, text='Enter Target Resistance In Ohms', bg='#ffc773')
myLabel.pack(pady=10)
e5 = Entry(root, width=10, justify='center', border=0)
e5.pack()

Button(root, text='Calculate', command=turn_count).pack(pady=40)

myLabel = Label(root, text='Turn Count', bg='#ffc773')
myLabel.pack()

count_label = Label(root, width=10)
count_label.pack()

Button(root, text='Reset', command=clear_fields).pack(pady=30)

root.mainloop()

这似乎是字典的一个很好的用例。也许使用 key:value 对对应于 value:alternate 值对的字典?对于选择的键,您将传递值。将此与 optionmenu 中的 command 选项结合使用以获得所需的效果。

option_keys = [38, 39, 42]
options = {'38':'1234',
           '39':'5678',
           '42':'2143'} # example provided

然后你会这样调用:

from tkinter import *

def func(value):
    print(options[value])

root = Tk()
var = StringVar()
drop = OptionMenu(root, var, *option_keys, command=func)
drop.place(x=10, y=10)

添加到,您可以执行以下操作来实现它

options = {
    '42':2143.0,
    '38':1234.0,
    '39':5678.0
}

clicked = StringVar()
clicked.set(list(options.keys())[0])

drop = OptionMenu(root, clicked, *options.keys())
drop.pack()

请注意,我使用了 StringVar 而不是 IntVar,因为字典键是字符串,当使用 get 方法时,我们需要它 return 一个字符串它。您可以直接将值设置为 float 并避免稍后强制转换它。

ohms = options[clicked.get()]