【问题标题】:How to get a function to change what's in the parameter of a previous function?如何获得一个函数来更改前一个函数的参数中的内容?
【发布时间】:2023-03-31 22:52:01
【问题描述】:

假设我有一个这样的函数:

def test_function(select):  
    function_test(testing)  

在 tkinter 中还有一个像这样的三个单选按钮:

selection = IntVar()
test1= Radiobutton(archive_buttons, text = 'Test Function', variable = selection, value = 1)
test2 = Radiobutton(archive_buttons, text = 'Test Function', variable = selection, value = 2)
test3 = Radiobutton(archive_buttons, text = 'Test Function', variable = selection, value = 3)

我正在尝试创建如下所示的函数。它试图将第一个函数中function_test(testing) 的参数中的内容更改为选项列表中的一个html 选项。

def select():
  options = ['hi.html', 'hello.html', 'hey.html'}
  counter = 1
  global testing
  for option in options:
    if selection.get() == options[counter]:
        testing = options[counter]
        counter = counter + 1
  return testing

因此,当我在 tkinter GUI 上单击如下按钮时,当在同一个 GUI 中选择了一个单选按钮时,我希望它在第一个函数中的 function_test(testing) 参数已经预先更改(结果我在我的 GUI 上选择一个单选按钮)。

extract_news_button = Button(function_buttons, text = 'Extract News', command = test_function, pady = 4)

但是,我收到此错误:

line 15, in select
  return testing
 NameError: name 'testing' is not defined

我怎样才能让它像我想要的那样工作?

【问题讨论】:

    标签: python function for-loop if-statement tkinter


    【解决方案1】:

    您的代码中的一切似乎都很好,您得到的错误是因为您试图全球化一个未声明的变量。 尝试在select() 函数之外声明变量testing。类似的东西

    testing = ''
    

    或者,如果您没有在select() 函数之外使用testing,只需删除以下行:global testing

    【讨论】:

    • 是的,您似乎对testing = ' ' 是正确的,但由于某种原因,没有弹出错误并且我的按钮没有任何作用。我将测试变量放在test_function(select) 函数之前
    • 检查并确保所有函数都以正确的顺序调用。您是否注意到,在将select 传递给test_function() 时,您只是传递了函数对象,而select() 实际上并没有被调用。
    猜你喜欢
    • 1970-01-01
    • 2022-11-21
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多