按下按钮时绑定ttkCombobox - Python

时间:2017-08-30 04:52:20

标签: python tkinter combobox

我使用的是Python 3.6.0,只有当我点击我的"确认结果"我才想保存我的组合框的价值。按钮。我做了很多搜索 - 但也许我的术语错了 - 我找不到这样做的方法。

我假设问题出在我的行 self.firstfaction_ent.bind(" Button-1",self.firstfaction_onEnter)。我非常有信心" Button-1"是不正确的 - 但我一直在尝试一切。

from tkinter import *
from tkinter import ttk

class Application(Frame):

   def __init__(self, master):

# Initialise the Frame
      super(Application, self).__init__(master)
      self.grid()
      self.create_widgets()

   def create_widgets(self):

   #Define Combobox for Faction
       self.firstfaction_ent=ttk.Combobox(self,textvariable=varSymbol, state='readonly')
       self.firstfaction_ent.bind("<Button-1>", self.firstfaction_onEnter)      
       self.firstfaction_ent['values']=Faction
       self.firstfaction_ent.grid(row=2, column=1)

  #create a submit button
       self.enter_bttn = Button(self,text = "Confirm Your Results", command = self.firstfaction_onEnter).grid(row=7, column=1)

   def firstfaction_onEnter(self, event):
       Faction_First = varSymbol.get()
       print(Faction_First)

#main

root = Tk()

#Window Title & size
root.title("Sports Carnival Entry Window")
root.geometry("600x500")

varSymbol=StringVar(root, value='')
varSecondFaction=StringVar(root, value='')
Faction = ["Blue", "Green", "Yellow", "Red"]

#create a frame in the window
app = Application(root)

root.mainloop( )

1 个答案:

答案 0 :(得分:0)

您需要confirm_button来捕获combo box中的选择;没有必要将组合框选择绑定到捕获;您也不需要将活动传递给firstfaction_onEnter;您可以直接使用combo_box获取选择的值。

from tkinter import *
from tkinter import ttk

class Application(Frame):

   def __init__(self, master):

# Initialise the Frame
      super(Application, self).__init__(master)
      self.grid()
      self.create_widgets()

   def create_widgets(self):

   #Define Combobox for Faction
       self.firstfaction_ent = ttk.Combobox(self, textvariable=varSymbol, state='readonly')
#        self.firstfaction_ent.bind("<Button-1>", self.firstfaction_onEnter)      
       self.firstfaction_ent['values'] = Faction
       self.firstfaction_ent.grid(row=2, column=1)

  #create a submit button
       self.enter_bttn = Button(self, text="Confirm Your Results", command=self.firstfaction_onEnter).grid(row=7, column=1)

   def firstfaction_onEnter(self):
       Faction_First = self.firstfaction_ent.get()
       print(Faction_First)

#main

root = Tk()

#Window Title & size
root.title("Sports Carnival Entry Window")
root.geometry("600x500")

varSymbol=StringVar(root, value='')
varSecondFaction=StringVar(root, value='')
Faction = ["Blue", "Green", "Yellow", "Red"]

#create a frame in the window
app = Application(root)

root.mainloop( )