gui2.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. """
  2. 使用tkinter创建GUI
  3. - 使用画布绘图
  4. - 处理鼠标事件
  5. Version: 0.1
  6. Author: 骆昊
  7. Date: 2018-03-14
  8. """
  9. import tkinter
  10. def mouse_evt_handler(evt=None):
  11. row = round((evt.y - 20) / 40)
  12. col = round((evt.x - 20) / 40)
  13. pos_x = 40 * col
  14. pos_y = 40 * row
  15. canvas.create_oval(pos_x, pos_y, 40 + pos_x, 40 + pos_y, fill='black')
  16. top = tkinter.Tk()
  17. # 设置窗口尺寸
  18. top.geometry('620x620')
  19. # 设置窗口标题
  20. top.title('五子棋')
  21. # 设置窗口大小不可改变
  22. top.resizable(False, False)
  23. # 设置窗口置顶
  24. top.wm_attributes('-topmost', 1)
  25. canvas = tkinter.Canvas(top, width=600, height=600, bd=0, highlightthickness=0)
  26. canvas.bind('<Button-1>', mouse_evt_handler)
  27. canvas.create_rectangle(0, 0, 600, 600, fill='yellow', outline='white')
  28. for index in range(15):
  29. canvas.create_line(20, 20 + 40 * index, 580, 20 + 40 * index, fill='black')
  30. canvas.create_line(20 + 40 * index, 20, 20 + 40 * index, 580, fill='black')
  31. canvas.create_rectangle(15, 15, 585, 585, outline='black', width=4)
  32. canvas.pack()
  33. tkinter.mainloop()
  34. # 请思考如何用面向对象的编程思想对上面的代码进行封装