从Tkinter组合框中获取价值

时间:2019-05-29 03:32:39

标签: python tkinter

最终,我想将组合框中的值用作其他函数的参数,但是我认为,如果现在就可以将它们打印出来,就足够了。这就是我到目前为止所拥有的。

import tkinter as tk
from tkinter import ttk
import time

def ok():
    betType = betTypeVar.get()
    season = seasonVar.get()
    print(betType, season)

def CreateSimPreviousSeasonWindow():

    prevSeasonWindow = tk.Tk()

    #============= Bet Type Input =============#
    betTypeVar = tk.StringVar()

    betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
    betTypeChosen = ttk.Combobox(prevSeasonWindow, values=['Moneyline','Total'])
    betTypeChosen.grid(row=0, column=1)

    seasonVar = tk.StringVar()
    seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
    seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
    seasonChosen.grid(row=1,column=1)

    button = tk.Button(prevSeasonWindow, text='OK', command=ok)
    button.grid(row=2,column=0)

    prevSeasonWindow.mainloop()

这给了我

  File "C:[directory...]", line 6, in ok
    betType = betTypeVar.get()
NameError: name 'betTypeVar' is not defined

在我看来,这个错误很明显是因为ok()没有任何参数传递给它,所以它不知道'betTypeVar'是什么,但是我阅读过的所有教程都是这样做的,所以我缺少了一些东西。如果我尝试实际传递ok()参数,它仍然不起作用。

1 个答案:

答案 0 :(得分:1)

您的代码中有两点要修复。首先让我们关注CreateSimPreviousSeasonWindow

betTypeVar = tk.StringVar()
seasonVar = tk.StringVar()

您定义了两个StringVar,但实际上您从未使用过它,或将它们链接到combobox对象。正确的方法是将它们设置为textvaraible

betTypeChosen = ttk.Combobox(prevSeasonWindow, textvariable=betTypeVar, values=['Moneyline','Total'])
seasonChosen = ttk.Combobox(prevSeasonWindow, textvariable=seasonVar, values=['2018', '2017'])

接下来,NameError: name 'betTypeVar' is not defined是由于您的变量是局部变量。您试图跨不同的函数访问相同的变量。要传递它们,您需要声明global

def ok():
    global betTypeVar, seasonVar
    betType = betTypeVar.get()
    season = seasonVar.get()
    print(betType, season)

def CreateSimPreviousSeasonWindow():
    global betTypeVar, seasonVar
    ...

我还要指出,如果只想检索组合框的值,则实际上并不需要创建两个StringVar。只是combobox.get()已经足够好了。

import tkinter as tk
from tkinter import ttk
import time

def ok():
    global betTypeChosen, seasonChosen
    print (betTypeChosen.get(), seasonChosen.get())

def CreateSimPreviousSeasonWindow():
    global betTypeChosen,seasonChosen

    prevSeasonWindow = tk.Tk()

    #============= Bet Type Input =============#

    betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
    betTypeChosen = ttk.Combobox(prevSeasonWindow,values=['Moneyline','Total'])
    betTypeChosen.grid(row=0, column=1)

    seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
    seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
    seasonChosen.grid(row=1,column=1)

    button = tk.Button(prevSeasonWindow, text='OK', command=ok)
    button.grid(row=2,column=0)

    prevSeasonWindow.mainloop()

CreateSimPreviousSeasonWindow()