2017-04-13 83 views
0

我正在使用tkinter編寫GUI,我希望窗口中的按鈕以某種方式更改眼睛和臉部。我無法定義我的功能來更改圓圈和線條。我想我可以自己撥打create_line來更改畫布中的繪圖。在我定義w之後,我嘗試將我的define語句移動到我的程序底部,但沒有運氣。我得到的錯誤,如'App' object has no attribute 'create_line' 我是非常新的python,所以任何反饋將不勝感激。定義tkinter按鈕命令來更改幀中的畫布

# 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

你需要說什麼樣的麻煩。你只用一個修改按鈕就可以更好地進行實驗。 REad https://stackoverflow.com/help/mcve –

回答

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()