Radiobutton值为None

时间:2016-02-20 04:50:35

标签: python tkinter

所以,我在Tkinter中创建了一个数据输入窗口,窗口中有“性别”选项,但是我无法确定选择哪个性别。 我的代码:

from Tkinter import *
import tkMessageBox

data_list = []

class Personal_Data:

    def __init__ (self, sex, age, height, weight):

        self.sex = sex
        self.age = age
        self.height = height
        self.weight = weight

def save_data (sex, age, height, weight, screen):

    screen.destroy ()
    data = Personal_Data (sex, age, height, weight)
    data_list.append (data)
    tkMessageBox.showinfo ("", "Entry saved!")

def data_entry ():

    data_entry_screen = Tk ()
    Label (data_entry_screen, text = "Sex:").grid (row = 0, column = 0)
    var = StringVar ()
    def sel ():
        print var.get ()
    male_pick = Radiobutton (data_entry_screen, text = "Male", variable = var, value = "Male", command = sel)
    male_pick.grid (row = 0, column = 1, sticky = "W")
    female_pick = Radiobutton (data_entry_screen, text = "Female", variable = var, value = "Female", command = sel)
    female_pick.grid (row = 0, column = 1, sticky = "E")
    sex = var.get ()
    Label (data_entry_screen, text = "Age:").grid (row = 1, column = 0)
    age_entry = Entry (data_entry_screen)
    age_entry.grid (row = 1, column = 1)
    Label (data_entry_screen, text = "Height:").grid (row = 2, column = 0)
    height_entry = Entry (data_entry_screen)
    height_entry.grid (row = 2, column = 1)
    Label (data_entry_screen, text = "Weight:").grid (row = 3, column = 0)
    weight_entry = Entry (data_entry_screen)
    weight_entry.grid (row = 3, column = 1)
    Button (data_entry_screen, text = "SAVE", command = lambda: \
            save_data (sex, age_entry.get(), height_entry.get(),\
                              weight_entry.get(), data_entry_screen)\
            ).grid (row = 4, column = 0)
    Button (data_entry_screen, text = "CANCEL", command = \
            data_entry_screen.destroy).grid (row = 4, column = 1)
root = Tk ()
root.title ("Main menu")
main_menu = Menu (root)

data_entry_menu = Menu (main_menu, tearoff = 0)
main_menu.add_cascade (label = "Data", menu = data_entry_menu)
data_entry_menu.add_command (label = "Data entry", command = data_entry)

root.config (menu = main_menu)

root.mainloop ()

实际上,它返回的值是None(我可以看到用sel函数打印的返回值),但我不知道为什么......有什么想法吗?

P.S。对不起,长代码,但它杀了我......

1 个答案:

答案 0 :(得分:0)

我不知道sex的值是None,但我确实知道它在哪里是空字符串''。您正在创建和设置新窗口时立即执行sex = var.get()(顺便说一下,应该使用Toplevel(),而不是另一个根对象)。由于此时它不是set(),因此它是空字符串''。稍后更改该按钮的选定值不会影响该保存的值。相反,请删除sex = var.get()并仅在" SAVE"时检索单选按钮的值。单击按钮,就像您已经在处理所有其他输入的数据一样:

...save_data(var.get(), age_entry.get(),...