![](/img/trans.png)
[英]Is there a way of using Python/Tkinter Canvas's highlightthickness using turtle?
[英]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.