如何使用python3.4中的按钮将值转换为函数

2024-04-20 11:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更改从Tkinter按钮调用的函数中的“number”,如下面的function2function1识别“数字”并正常工作,function2给出一个UnboundLocalError。如果我试图传递按钮中的值(比如:command=function2(number)),那么函数将立即执行,而不必按按钮。有人能帮忙吗?你知道吗

from tkinter import *

def function1():
    print('In pcomm.')
    print('number=', str(number))

def function2():
    print('In acomm.')
    print('number=', str(number))
    number += 1  #UnboundLocalError: local variable 'number' referenced before assignment
    print('number=', str(number))

#create the window
root = Tk()

number = 2
print('Just assigned: number=', str(number))

printButton = Button(root, text = "Press to print.", command = function1).grid()
addButton = Button(root, text = "Press for number+=1.", command = function2).grid()


#kick off the event loop
root.mainloop()

Tags: the函数textinnumberdefbuttonroot
1条回答
网友
1楼 · 发布于 2024-04-20 11:30:13

为了避免全局性,您需要使用一个类。你知道吗

class AppData(object):
    def __init__(self):
        self.number = 2

    def function1(self):
        print('In pcomm.')
        print('number=', str(self.number))

    def function2(self):
        print('In acomm.')
        print('number=', str(self.number))
        self.number += 1
        print('number=', str(self.number))

然后创建类的实例,并将其绑定的方法传递给按钮。。。你知道吗

app = AppData()
addButton = Button(root, text = "Press for number+=1.", command = app.function2)
addButton.grid()

注意,您经常会看到按钮是另一个(或同一个)类的一部分。你知道吗

相关问题 更多 >