定义tkinter按钮命令以更改框架中的画布

时间:2017-04-13 20:38:08

标签: python tkinter

我正在使用tkinter编写GUI,我希望窗口中的按钮以某种方式改变眼睛和脸部。我无法定义我的功能来更改圆圈和线条。我以为我可以在自己上调用create_line来更改画布中的绘图。在我定义define之后,我尝试将我的w语句移到我的程序的底部,但没有运气。我收到'App' object has no attribute 'create_line'等错误 我是python的新手,所以任何反馈都会受到赞赏。

# import tkinter
from tkinter import *

# define a new class
class App:

  # define a command talk
  def talk(self):
    print("Talk button clicked...")
    #w.self.create_line(45, 100, 90, 110)

  # window of the GUI
  def __init__(self, master):
    # parent window
    frame = Frame(master, bg = "#76F015")

    # organizes the widgets into blocks
    frame.pack()

    # define a button in the parent window
    self.button = Button(frame, text = "Talk", highlightbackground = "#D4D6D3", 
       fg = "black", command = self.talk)
    self.button.pack(side = RIGHT)

    # define a canvas
    w = Canvas(frame, width = 125, height = 175, bg = "#76F015")
    w.pack()

    # draw a mouth
    w.create_line(45, 100, 85, 100)


# run the main event loop
root = Tk()
app = App(root)
root.mainloop()

1 个答案:

答案 0 :(得分:0)

这是一个有效的例子:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)

        self.face = Face(self, width = 125, height = 175, bg = "#76F015")
        self.face.pack()

        btn = tk.Button(self, text="Smile", command=self.face.smile)
        btn.pack()

        btn = tk.Button(self, text="Normal", command=self.face.normal_mouth)
        btn.pack()

        btn = tk.Button(self, text="Quick smile", command=self.quick_smile)
        btn.pack()

    def quick_smile(self):
        self.face.smile()
        self.after(500, self.face.normal_mouth) # return to normal after .5 seconds

class Face(tk.Canvas):
    def __init__(self, master=None, **kwargs):
        tk.Canvas.__init__(self, master, **kwargs)

        # make outside circle
        self.create_oval(25, 40, 105, 120)

        # make eyes
        self.create_oval(40, 55, 60, 75)
        self.create_oval(70, 55, 90, 75)

        # make initial mouth
        self.mouth = [] #list of things in the mouth
        self.normal_mouth()

    def smile(self):
        self.clear(self.mouth) # clear off the previous mouth
        self.mouth = [
            self.create_arc(45, 80, 85, 100, start=180, extent=180)
            ]

    def normal_mouth(self):
        self.clear(self.mouth) # clear off the previous mouth
        self.mouth = [
            self.create_line(45, 100, 85, 100),
            self.create_arc(25, 95, 45, 105, extent=90, start=-45, style='arc'), # dimple
            self.create_arc(85, 95, 105, 105, extent=90, start=135, style='arc') # dimple
            ]

    def clear(self, items):
        '''delete all the items'''
        for item in items:
            self.delete(item)

def main():
    root = tk.Tk()
    win = App(root)
    win.pack()
    root.mainloop()

if __name__ == '__main__':
    main()