如何让这个函数显示变量?

时间:2014-05-17 05:06:42

标签: python tkinter

string_one = "this is string one"
string_two = "this is string two"

def choose_number():
    if radio_value.get() == 'One':
        number = string_one
    elif radio_value.get() == 'Two':
        numbers = string_two

    print numbers

我正在尝试在选择单选按钮时显示数字变量

如果我运行此代码,则会收到错误消息,指出数字未定义。但是,如果我在函数中放置数字,则第二个单选按钮将不起作用

1 个答案:

答案 0 :(得分:2)

这里有两个问题:

  • number = string_one - 你可能意味着numbers = string_one
  • 如果numbers不是radio_value.get()One,则
  • Two未定义。您需要else

    def choose_number():
        if radio_value.get() == 'One':
            numbers = string_one
        elif radio_value.get() == 'Two':
            numbers = string_two
        else:
            numbers = 'Not Found'
    
        print numbers
    

更好地定义字典映射并使用get()并提供默认值,以防未找到值:

mapping = {'One': "this is string one",
           'Two': "this is string two"}

def choose_number():
    print mapping.get(radio_value.get(), 'Not Found')