Tkinter按钮参数

时间:2018-08-10 13:20:05

标签: python tkinter

我最近开始学习python。我在gui方面的经验很少,想了解更多信息。经过很少的研究,我发现tkinter使其成为现实。作为一个项目,决定让游戏成为策划者。

我正在做的是使用OptionMenu在行中放置可用的颜色。在右侧,我放置了一个确认按钮,该按钮设置了“验证”命令。问题是,我想使用以下代码将不同的值传递给每个按钮(框架和行),但我遇到的问题是它说行始终为9。

我想过一种可能的解决方案,即在y = 0的末尾重置,并在每次按下按钮add 1时重置。但是我认为它应该更简单。

from tkinter import *

def selectedColor(var):
    print("Value is: " + var)

def validate(frame, row):
    # pass
    print("Frame: " + str(frame) + " row: " + str(row))
    rowToValidate = frame.nametowidget("." + str(row))
    for x in range(0,4):
        columnValue = frame.nametowidget("." + str(x) + str(row))
        print(columnValue)

master = Tk()

OPTIONS

 = [
    "RED",
    "BLUE",
    "YELLOW",
    "VIOLET",
    "ORANGE",
    "GREEN",
    "BROWN",
    "WHITE",
    "BLACK"
]

colorQuantity = 4
tries = 10
for y in range(0, tries):
    frame = Frame(master, name=str(y))
    isEnabled = "disabled" if y != 0 else "normal"
    for x in range(0,colorQuantity):
        variable = StringVar(frame, name=str(x)+str(y))
        variable.set("Choose color") # default value
        # print(str(variable))

        w = OptionMenu(frame, variable, *OPTIONS, command=selectedColor)        
        w.configure(state=isEnabled)
        w.pack(side=LEFT)
    confirmButton = Button(frame, text="Confirm", command= lambda: validate(frame, y+1))
    confirmButton.configure()
    confirmButton.pack(side=TOP)
    print(str(frame))
    frame.pack(side=TOP)


master.mainloop()   

1 个答案:

答案 0 :(得分:1)

我会将OptionMenu变量保存在列表中,以使其更易于检索其值。通过在命令选项中使用partiallink),可以确保每一行都获得正确的行号作为输入。

请参见下面的代码(我还在下拉菜单中添加了一些格式设置):


from tkinter import *
from functools import partial

def selectedColor(var):
    print("Value is: " + var)

def validate(args):
    frame = args[0]
    row = args[1]

    for x in range(0,4):
        print(rows[row][x].get())

master = Tk()

OPTIONS = [
    "RED",
    "BLUE",
    "YELLOW",
    "VIOLET",
    "ORANGE",
    "GREEN",
    "BROWN",
    "WHITE",
    "BLACK"
]

colorQuantity = 4
tries = 10
rows =[]
for y in range(0, tries):
    frame = Frame(master, name=str(y))
    isEnabled = "disabled" if y != 0 else "normal"
    row = []
    for x in range(0,colorQuantity):
        variable = StringVar(frame, name=str(x)+str(y))
        variable.set("Choose color") # default value
        # print(str(variable))
        row.append(variable)

        w = OptionMenu(frame, variable, *OPTIONS, command=selectedColor)  
        w.configure(width=len("Choose color"))      
        w.configure(state=isEnabled)
        w.pack(side=LEFT)
    rows.append(row)
    confirmButton = Button(frame, text="Confirm", command=partial(validate,(frame, y)))
    confirmButton.configure()
    confirmButton.pack(side=TOP)
    print(str(frame))
    frame.pack(side=TOP)


master.mainloop()