繁体   English   中英

Python Turtle 不在 Tkinter 画布中,而按钮不在角落

[英]Python Turtle not in Tkinter Canvas & Button not in Corner

我正在用 Tkinter 的 Canvas 模块创建一个带有海龟的游戏。 我遇到了一个问题,当我尝试生成一只新海龟时,它会在新窗口而不是画布中生成。 我做错了什么? 我还想通过退出按钮解决我的问题。 我一直试图把它放在右下角。 我试过.place().grid()但没有成功。 我也在 stackoverflow 上尝试了其他解决方案,但它们要么导致错误,要么就消失了,可能在画布后面。

这是我的代码:

import tkinter as tk
import random
import turtle
import time
import sys

def spawn(e=None):
    xrand = random.randint(0,500)
    yrand = random.randint(0,500)
    turtle.RawTurtle(app)
    turtle.shape("square")
    turtle.penup()
    turtle.goto(x=xrand,y=yrand)

def systemap(e=None):
    app.pack()
    button.pack()

def f(e=None):
    t.setheading(90)
    t.forward(1)

def l(e=None):
    t.setheading(180)
    t.forward(1)

def r(e=None):
    t.setheading(0)
    t.forward(1)

def b(e=None):
    t.setheading(270)
    t.forward(1)

def quit(e=None):
    time.sleep(1)
    window.destroy()
    sys.exit()

window = tk.Tk()
#window.iconbitmap('py.ico')
window.title("Turtle Graphics")
window.geometry("750x500")
window.resizable(False, False)

button = tk.Button(window, text="Exit", command = quit)

app = tk.Canvas(master=window, width=500, height=500, bg="white")

t=turtle.RawTurtle(app)

window.bind("<Up>", f)
window.bind("<Left>", l)
window.bind("<Right>", r)
window.bind("<Down>", b)

window.bind("<w>", f)
window.bind("<a>", l)
window.bind("<d>", r)
window.bind("<s>", b)

window.bind("<e>", spawn)

window.bind("<Escape>", quit)

systemap()

window.mainloop()


我发现您必须在窗口中的所有内容上使用.pack().grid()否则它将无法工作,因此您无法使用.pack()一些文本使用.grid() 所以你可以在所有需要进入窗口的东西上使用 .place 把它们放在你需要的地方,所以它会是这样的:

import tkinter as tk
import random
import turtle
import time
import sys

def systemap(e=None):
    app.place(x=100,y=-4)
    button.place(x=720,y=475)

def f(e=None):
    t.setheading(90)
    t.forward(1)

def l(e=None):
    t.setheading(180)
    t.forward(1)

def r(e=None):
    t.setheading(0)
    t.forward(1)

def b(e=None):
    t.setheading(270)
    t.forward(1)

def quit(e=None):
    time.sleep(1)
    window.destroy()
    sys.exit()

window = tk.Tk()
window.iconbitmap('py.ico')
window.title("Turtle Graphics")
window.geometry("750x500")
window.resizable(False, False)

button = tk.Button(window, text="Exit", command = quit)

app = tk.Canvas(master=window, width=500, height=500, bg="white")

t=turtle.RawTurtle(app)

window.bind("<Up>", f)
window.bind("<Left>", l)
window.bind("<Right>", r)
window.bind("<Down>", b)

window.bind("<w>", f)
window.bind("<a>", l)
window.bind("<d>", r)
window.bind("<s>", b)

window.bind("<Escape>", quit)

systemap()

window.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM