Skip to main content
 首页 » 编程设计

python之如何使用笔记本中的组合框以 python 形式进行计算

2025年05月04日13jiqing9006

很抱歉再次打扰你,因为我是 Python 的新手问题。我正在尝试使用组合框在 python 中进行简单的计算(乘法),但我不知道如何进行。下面你会发现我到目前为止所做的没有成功。希望你能帮助我!

非常感谢您

这是我的代码:

import Tkinter 
 
root = Tk() 
root.title("Model A") 
root.minsize(400, 220) 
root.maxsize(410, 240) 
 
# start of Notebook (multiple tabs) 
notebook = ttk.Notebook(root) 
notebook.pack(fill='both', expand='yes') 
notebook.pressed_index = None 
 
# child frames 
frameOne = Tkinter.Frame(notebook, bg='white',width=560, height=100) 
 
frameOne.pack(fill='both', expand=True) 
# pages 
notebook.add(frameOne, text='Simple calculation') 
 
#Close Application Button 
def quit(root): 
    root.destroy() 
tk.Button(root, text="Close Application", command=lambda root=root:quit(root)).pack() 
 
## Calculation 
def defocus(event): 
    event.widget.master.focus_set() 
def multiply(*args): 
    try: 
        product.config(round(float(Num_One.get())*float(Num_Two.get()))) 
    except ValueError: 
        pass 
 
## variables 
Num_One = StringVar() 
Num_Two = StringVar() 
product = DoubleVar() 
#Number One 
ttk.Label(frameOne, text="Select First Number:").grid(column =3, row = 0) 
NumOne_Select = Combobox(frameOne, values=("1", "2", "3","4", "5"),textvariable=Num_One) 
NumOne_Select.grid(column=4, row=0, columnspan="5", sticky="nswe") 
NumOne_Select.bind('<KeyPress>', multiply) 
NumOne_Select.bind('<KeyRelease>', multiply) 
 
#Number two 
ttk.Label(frameOne, text="Select Second Number:").grid(column =3, row = 6 ) 
NumTwo_Select = Combobox(frameOne, values=("1", "2", "3","4", "5"),textvariable=Num_Two) 
NumTwo_Select.grid(column=4, row=6, columnspan="5", sticky="nswe") 
NumTwo_Select.bind('<KeyPress>', multiply) 
NumTwo_Select.bind('<KeyRelease>', multiply) 
 
# display results 
ttk.Label(frameOne, text = "Product:").grid(column = 3, row = 8) 
ttk.Label(frameOne, textvariable=product).grid(column = 4, row = 8) 
 
root.mainloop() 

请您参考如下方法:

由于您的代码实际上并没有运行,所以我无法告诉您它的所有问题……但我可以很容易地找出两个问题。

首先,在 multiply ,你在做product.config .那不是你的DoubleVar的值(value).你几乎肯定想要 product.set在这里。

其次,您正在尝试使用 <KeyRelease> 捕获所有更改.例如,如果您使用鼠标从剪贴板粘贴,或使用下拉菜单更改值,则不会更新任何内容,因为没有按键释放事件。

您还绑定(bind)了 <KeyPress>因为某些原因。在正常使用中,这意味着您更新每个按键 Product使用旧值,然后立即使用新值再次更新它。如果有人按住一个键直到它重复,你会不断更新,但总是落后一个重复。

如果您想尝试以这种方式做事,我相信您至少需要绑定(bind)这些事件:

  • <KeyRelease> (而不是 <KeyPress> )
  • <<ComboboxSelected>>
  • <<Clear>>
  • <<Cut>>
  • <<Paste>>

那么,还有什么方法可以做到呢?好吧,有几个,我真的不确定哪个是最pythonic的(或Tk-ish?); Tk 是 TOOWTDI 不支持的 Python 少数几个领域之一。但我想我会通过 Hook 每个 StringVar 的更新来做到这一点, 而不是每个 Combobox .扔掉 bind调用,而是这样做:

Num_One.trace("w", multiply) 
Num_Two.trace("w", multiply)