Select 使用组合框的字符串并存储在 Tkinter window 关闭后使用的变量中

Select a string using a Combobox and store in variable to be used after the Tkinter window closes

我创建了一个简单的 window 供用户使用 Combobox.

输入一些字符串

我已经成功创建了下拉列表和一个关闭按钮 window,但我在尝试将所选值存储在变量中以供下一部分使用时遇到问题程序。

# start programme window
root = tk.Tk()
root.title('Great Britain Basketball')
root.geometry('800x449+300+130')
root.configure(bg='#072462')

#def variable and store based on selection
def comboclick(event):
    select_sheet = cb.get()

#create combobox
cb = ttk.Combobox(root, value=('Mon', 'Tues', 'Wed', 'Thurs'))
cb.current(0)
cb.bind('<<ComboboxSelected>>', comboclick)
cb.pack()

#set close window button
button_close = Button(root, width=35, text='Close Programme', command=root.quit, 
                      fg='#C51E42', bg='#B4B5B4', borderwidth=1).pack()

root.mainloop()

print(select_sheet)

我尝试使用 .get() 定义组合框 (cb) 的选择,但是当我尝试在程序继续时打印变量时,我收到错误

  print(select_sheet)
NameError: name 'select_sheet' is not defined

我把select_sheed声明为一个全局变量,所以可以在函数内部修改,我也给select_sheet插入了一个起始值,所以如果用户不改变组合框的值,他仍然会得到一个值。

这些是为了使其正常工作而必须进行的最小更改。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title('Great Britain Basketball')
root.geometry('800x449+300+130')
root.configure(bg='#072462')

#def variable and store based on selection
def comboclick(event):
    global select_sheet # Setting select_sheet to global, so it can be modified
    select_sheet = cb.get()

# I am setting here the same value of cb.current(), so if the user doesn't change it, you still get an output.
select_sheet = 'Mon'

#create combobox
cb = ttk.Combobox(root, value=('Mon', 'Tues', 'Wed', 'Thurs'))
cb.current(0)
cb.bind('<<ComboboxSelected>>', comboclick)
cb.pack()

#set close window button
button_close = tk.Button(root, width=35, text='Close Programme', command=root.quit, 
                      fg='#C51E42', bg='#B4B5B4', borderwidth=1).pack()

root.mainloop()

print(select_sheet)