Tkinter Combobox有两个变量

时间:2017-11-09 16:05:28

标签: python tkinter

 from tkinter import *
 from tkinter import ttk
 from random import *

class Application(Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self.grid()
        self.c = randint(1, 50)
        self.o = randint(60, 100)
        varClose.set(self.c)
        varOpen.set(self.o)
        Close = varClose.get()
        Open = varOpen.get()
        self.Mylist = ttk.Combobox(width=10)
        self.Mylist['values'] = (Close, Open)
        self.Mylist.grid(row=1, column=6, sticky=W)


root = Tk()
root.geometry('420x220')
varClose = IntVar(root, value='Close')
varOpen = IntVar(root, value='Open')
app = Application(root)

root.mainloop()

我不确定如何在下拉菜单中显示关闭和打开。相反,我得到了值,默认字段为空。如何在菜单中以与从randint收到的值相关的方式关闭和打开? 我想进一步将这些值用于其他操作。

1 个答案:

答案 0 :(得分:0)

您可以将它们存储为元组:

from tkinter import *
from tkinter import ttk
from random import *

class Application(Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self.grid()
        self.c = randint(1, 50)
        self.o = randint(60, 100)
        varClose[0].set(self.c)
        varOpen[0].set(self.o)
        Close = varClose[1]
        Open = varOpen[1]
        self.Mylist = ttk.Combobox(width=10)
        self.Mylist['values'] = (Close, Open)
        self.Mylist.grid(row=1, column=6, sticky=W)


root = Tk()
root.geometry('420x220')
varClose = (IntVar(root), "Close")
varOpen = (IntVar(root), "Open")
app = Application(root)

root.mainloop()

这意味着VarCloseVarOpen实际上变成了一个包含两个值的变量,第一个是IntVar(),它设置为您运行的randint()的值,以及"Close""Open"的字符串。

这样做意味着您将两个值(字符串和随机数)存储在同一个变量中,因此它们之间具有易于访问的关系。

作为参考,您也可以使用列表执行此操作:

from tkinter import *
from tkinter import ttk
from random import *

class Application(Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self.grid()
        self.c = randint(1, 50)
        self.o = randint(60, 100)
        varClose[0].set(self.c)
        varOpen[0].set(self.o)
        Close = varClose[1]
        Open = varOpen[1]
        self.Mylist = ttk.Combobox(width=10)
        self.Mylist['values'] = (Close, Open)
        self.Mylist.grid(row=1, column=6, sticky=W)


root = Tk()
root.geometry('420x220')
varClose = [IntVar(root), "Close"]
varOpen = [IntVar(root), "Open"]
app = Application(root)

root.mainloop()