【发布时间】:2024-04-17 17:55:01
【问题描述】:
我想添加用户从不同组合框中选择的多个值。然后我想将这些值加在一起并在框旁边显示总值。问题似乎是组合框中的“值”是字符串,因此不能加在一起。 如果你想运行程序,只需在最后一个 for 循环之前注释掉变量“totalvalues”。(我知道它看起来很奇怪,我只是试图制作一个新程序来显示我的问题)
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
win=tk.Tk() #window
win.title("Moskalkylator")
antalcomboboxes=4
mighty=ttk.LabelFrame(win,text='Welcome')
mighty.grid(column=0,row=0,padx=8 ,pady=4)
Items=['Wood','Iron','Plastic','Glass']
def click():
calculate = ttk.Label(win, text="Your total number of items is : " + totalvalues.get()) # See row 27
calculate.grid(column=1, row=0)
buttons_frame=ttk.LabelFrame(mighty)
buttons_frame.grid(column=1,row=8, padx=3, pady=3,sticky=tk.W)
calculate=ttk.Button(buttons_frame,text='Count', command=click).grid(column=1,row=8)
#Creates combobox 1
list1=list(range(11))
number_chosen1= ttk.Combobox(mighty,values=list1, state="readonly") #The number you pick in the combobox
number_chosen1.grid(column=1,row=1,sticky=tk.W)
#Creates combobox 2
list2=list(range(11))
number_chosen2= ttk.Combobox(mighty,values=list2, state="readonly")
number_chosen2.grid(column=1,row=3,sticky=tk.W)
###############
totalvalues=number_chosen1+number_chosen2 #This does not work! COMMENT THIS
###############
#Loop to get the names of the items above combobox
Items_order=0
row_move_loop2=0
for element in Items:
article = ttk.Label(mighty, text=Items[Items_order])
article.grid(column=1, row=row_move_loop2)
Items_order=Items_order+1
row_move_loop2=row_move_loop2+2
win.mainloop()
【问题讨论】:
-
值是数字的字符串表示形式吗?就像它是“5”而不是5?如果是这样,您只需使用“int”关键字将值转换为整数。例如 int(value)。
-
我试过了,但无法让它工作,我的错误消息指出:+:'Combobox' 和'Combobox' 的操作数类型不受支持。如果我在控制台中将“值”(我在组合框中选择的数字)打印为 print(number_chosen1),我会得到“.!labelframe.!combobox”
-
那是因为你添加的是组合框+组合框不是它们的值。你需要获取组合框的值然后添加它们。
标签: python string tkinter combobox integer