使用tkinters button命令访问类外部的类方法

时间:2018-02-16 20:57:44

标签: python python-3.x tkinter

我在尝试从tkinters按钮上的命令调用类的方法时遇到问题。我试过了:

command = Alarm_clock.save_alarm()
command = self.save_alarm()
command = Alarm_clock.save_alarm(self.hour_count, self.min_count)
command = Alarm_clock.save_alarm(self)

我认为我错过了一些明显的东西,因为我已经设法在同一个班级中“命令”了方法。

以下是我的代码片段:它是一个闹钟:

import tkinter as tk
import time
import vlc
import pygame
from mutagen.mp3 import MP3

class Alarm_clock():
    def __init__(self):
        alarm_list = []

    def save_alarm(self):
        print(init_alarm_gui.hour_count.get())
        print(init_alarm_gui.min_count.get())
        #get the hour and minute and append it to the alarm_list to be checked on real time

class init_alarm_gui():
    def __init__(self, root):
        self.root = root
        self.hour_count = 0
        self.min_count = 0

    def make_widgets(self, root):

        self.hour_count = tk.IntVar()

        self.min_count = tk.IntVar()

        self.time_label = tk.Label(text="")
        self.time_label.pack()

        self.Save_but = tk.Button(root, text = "Save Alarm", command=Alarm_clock.save_alarm)
        self.Save_but.pack()  

def main():
    root = tk.Tk()
    gui = init_alarm_gui(root)
    gui.make_widgets(root)    
    root.mainloop()   

if __name__ == "__main__":
    main()

TyperError: save_alarm() missing 1 required positional argument: 'self'

1 个答案:

答案 0 :(得分:1)

您必须创建该类的实例,然后调用该实例的方法。这将自动填写self参数。这不是tkinter独有的,它只是python的工作方式。

alarm = Alarm_clock()
alarm.save_alarm()