如何将 Turle 绘图添加到 Tkinter 中另一个按钮中的按钮?

问题描述 投票:0回答:1
import turtle
from random import randint
import tkinter as tk
from turtle import ScrolledCanvas, RawTurtle, TurtleScreen


root = tk.Tk()
root.geometry("600x500")
root["bg"]="Teal"
root.title("2.S.2.D")


def create_window():
  window = tk.Toplevel(root)
  window.geometry("400x250")
  a = tk.Button(window,text="Red", command=create_window_A)
  a.pack()
  b = tk.Button(window, text="Blue", command=create_window_B)
  b.pack()
  c = tk.Button(window, text="Green", command=create_window_C)
  c.pack()
  d = tk.Button(window, text="Grey", command=create_window_D)
  d.pack()

#Red Color
def create_window_A():
    windowA = tk.Toplevel(root)
    windowA.geometry("400x250")
    canvas = tk.Canvas(master=windowA, width=800, height=800)
    canvas.grid(padx=2, pady=2, row=0, column=0, rowspan=10, columnspan=10)
    draw = turtle.RawTurtle(canvas)
    def draw_square():
        brad = turtle.Turtle()
        brad.forward(100)
        brad.right(90)
        brad.forward(100)
        brad.right(90)
        brad.forward(100)
        brad.right(90)
        brad.forward(100)
        brad.right(90)
    Board_Button = tk.Button(master=windowA, text="Draw_Board", bg="cyan", fg="black",    command=draw_square)
    Board_Button.grid(padx=2, pady=2, row=1, column=11, sticky='nsew')
root.mainloop()`

以上是我无数次尝试之一。问题是会出现一个画布以及一个按钮。该按钮会打开一个海龟窗口并绘制所需的形状(正方形)。 然而,我想要实现的是,画布旁边的按钮将启动在画布中绘制正方形的命令,而不是打开另一个窗口。 还有三种颜色;蓝色、绿色和灰色。我只需要其中一个正确,然后我就可以复制并粘贴其余的。 非常感谢你

python tkinter button canvas python-turtle
1个回答
0
投票

如果您想在按钮旁边的画布中绘制正方形,则不应在内部创建另一个海龟对象

draw_square()

def create_window_A():
    windowA = tk.Toplevel(root)
    #windowA.geometry("400x250") # why create a window with size smaller than the canvas?
    canvas = tk.Canvas(master=windowA, width=800, height=800)
    canvas.grid(padx=2, pady=2, row=0, column=0, rowspan=10, columnspan=10)
    # changed draw to brad
    brad = turtle.RawTurtle(canvas)
    def draw_square():
        #brad = turtle.Turtle()  # don't create new turtle window
        # draw on the already created turtle canvas
        brad.forward(100)
        brad.right(90)
        brad.forward(100)
        brad.right(90)
        brad.forward(100)
        brad.right(90)
        brad.forward(100)
        brad.right(90)
    Board_Button = tk.Button(master=windowA, text="Draw_Board", bg="cyan", fg="black",    command=draw_square)
    Board_Button.grid(padx=2, pady=2, row=1, column=11, sticky='nsew')
© www.soinside.com 2019 - 2024. All rights reserved.