在python中获取组合框的值

Dam*_*ien 6 python combobox tkinter ttk

我正在开发一个简单的程序,我需要从Combobox. 当 is 在第一个创建的窗口中时,这很容易Combobox,但是例如,如果我有两个窗口并且Combobox在第二个窗口中,我无法从中读取值。

例如 :

from tkinter import *
from tkinter import ttk

def comando():
    print(box_value.get())

parent = Tk() #first created window
ciao=Tk()     #second created window
box_value=StringVar()
coltbox = ttk.Combobox(ciao, textvariable=box_value, state='readonly')
coltbox["values"] = ["prova","ciao","come","stai"]
coltbox.current(0)
coltbox.grid(row=0)
Button(ciao,text="Salva", command=comando, width=20).grid(row=1)
mainloop()
Run Code Online (Sandbox Code Playgroud)

如果我将小部件的父级更改为父ciao级,它就可以工作了!谁能给我解释一下吗?

小智 5

你不能有两个Tk()窗户。必须有一个Toplevel

要获取变量,你可以这样做box_value.get()

下拉框示例:

class TableDropDown(ttk.Combobox):
    def __init__(self, parent):
        self.current_table = tk.StringVar() # create variable for table
        ttk.Combobox.__init__(self, parent)#  init widget
        self.config(textvariable = self.current_table, state = "readonly", values = ["Customers", "Pets", "Invoices", "Prices"])
        self.current(0) # index of values for current table
        self.place(x = 50, y = 50, anchor = "w") # place drop down box 
        print(self.current_table.get())
Run Code Online (Sandbox Code Playgroud)