使用Tkinter编写应用程序需要添加具有相同功能的按钮。如何识别我点击的按钮并自动更改线?

时间:2013-11-27 17:05:28

标签: python tkinter

我想要的以下内容是添加多个不同的任务,并且有一个任务启动按钮,用于触发计时器。

class Pomodoro_app(Tk):
    def add_task(self):
        global time
        time = StringVar()
        time.set("Start")
        task_content = askstring(title = 'Add a Task', prompt = "Input a task")
        task_label   = Label(self, text = task_content, font = ("Arial, 12")).grid(column = 0, row = 3)
        task_start_button = Button(self, textvariable = time, command = self.start_working).grid(column = 1, row = 3)

    def createWidgets(self):
        self.welcome_label   = Label(self, text = "Welcome to the Challenge!", font = ("Arial, 12")).grid(column = 0, row = 0, columnspan = 2)

        self.add_task_button = Button(self, text = "Add Task", width = 20, command = self.add_task).grid(column = 0 , columnspan = 2)

    def __init__(self):
        """GUI Initiation"""
        Tk.__init__(self)
        self.createWidgets()
        """window Initiation"""
        self.resizable(False, False)
        x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
        y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
        self.geometry('250x400+%d+%d' % (x, y))

1 个答案:

答案 0 :(得分:0)

使用lambda(或内部函数),您可以将其他参数传递给回调。

例如:

class Pomodoro_app(Tk):
    def add_task(self):
        global time
        time = StringVar()
        time.set("Start")
        task_content = askstring(title = 'Add a Task', prompt = "Input a task")
        task_label   = Label(self, text = task_content, font = ("Arial, 12")).grid(column = 0, row = self.next_row)
        task_start_button = Button(self, textvariable = time, command = lambda: self.start_working(task_content)).grid(column = 1, row = self.next_row)
        #                                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        self.next_row += 1

    def start_working(self, task_name):
        print('start working', task_name)

    def createWidgets(self):
        self.welcome_label   = Label(self, text = "Welcome to the Challenge!", font = ("Arial, 12")).grid(column = 0, row = 0, columnspan = 2)
        self.add_task_button = Button(self, text = "Add Task", width = 20, command = self.add_task).grid(column = 0 , columnspan = 2)

    def __init__(self):
        """GUI Initiation"""
        Tk.__init__(self)
        self.createWidgets()
        """window Initiation"""
        self.resizable(False, False)
        x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
        y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
        self.geometry('250x400+%d+%d' % (x, y))
        self.next_row = 3