我有一部分这样的代码
import turtle
turtle.bgcolor("green")
draw = turtle.Turtle()
draw.speed(1000000)
draw.hideturtle()
draw.pensize(3)
draw.color("white")
def Board (a, x, y, size):
draw.pu()
draw.goto(x, y)
draw.pd()
for i in range (0, 4):
draw.forward(size)
draw.right(90)
x =-40
y = -40
size = 40
for i in range (0, 10):
for j in range (0, 10):
Board (draw, x + j*size, y + i*size, size)
turtle.done()
像这样
import tkinter
import tkinter.messagebox
window = tkinter.Tk()
def Button_click ():
tkinter.messagebox.showinfo("Game", "Tic Tac Toe")
button = tkinter.Button(window, text = "Play!", command = Button_click)
button.pack()
window.mainloop()
由于我试图创建一个带有按钮的窗口以进入TicTacToe游戏(我还没有完成剩下的,只剩下棋盘了)。有什么办法可以将乌龟和tkinter结合起来吗? 谢谢
答案 0 :(得分:0)
是的。 Python乌龟在较大的tkinter程序中以 standalone 和 embedded 两种模式运行。在使用乌龟嵌入时,可以使用Turtle
,Screen
和可选的RawTurtle
来代替TurtleScreen
和ScrolledCanvas
。您可以根据需要使用画布包含乌龟图形来构建tkinter界面。通过在SO中搜索RawTurtle
,可以找到在tkinter中嵌入乌龟的示例。
Here's an example of the same code written both embedded and standalone。
答案 1 :(得分:0)
当cdlane回答您的问题时,我正在处理您的代码!正如cdlane所说,我将“ turtle”替换为“ RawTurtle”,并将您的按钮与画布放在同一窗口上。在放置东西时,我更喜欢使用网格而不是打包,因为我感觉自己拥有更多的控制权。
import tkinter
import turtle
import tkinter.messagebox
window = tkinter.Tk()
canvas = tkinter.Canvas(master = window, width = 800, height = 800)
canvas.grid(padx=2, pady=2, row=0, column=0, rowspan=10, columnspan=10) # , sticky='nsew')
#draw = turtle.Turtle()
draw = turtle.RawTurtle(canvas)
def Board(a, x, y, size):
#draw.pu()
draw.penup()
draw.goto(x,y)
#draw.pd()
draw.pendown()
for i in range (0, 4):
draw.forward(size)
draw.right(90)
def Board2():
x =-40
y = -40
size = 40
for i in range (0, 10):
for j in range (0, 10):
Board(draw, x + j*size, y + i*size, size)
def Button_click ():
tkinter.messagebox.showinfo("Game", "Tic Tac Toe")
#button = tkinter.Button(window, text = "Play!", command = Button_click)
#button = Tk.Button(window, text = "Play!", command = Button_click)
#button.pack()
#
Play_Button = tkinter.Button(master = window, text ="Play!", command = Button_click)
Play_Button.config(bg="cyan",fg="black")
Play_Button.grid(padx=2, pady=2, row=0, column=11, sticky='nsew')
Board_Button = tkinter.Button(master = window, text ="Draw_Board", command = Board2)
Board_Button.config(bg="cyan",fg="black")
Board_Button.grid(padx=2, pady=2, row=1, column=11, sticky='nsew')
#
window.mainloop()