【发布时间】:2015-05-24 19:30:10
【问题描述】:
在下面的代码中,我希望第 34 行的 label 像第 59 行的 label 一样位于我的画布顶部。但它会转到我的画布底部,即使我在两个地方都使用相同的代码。
这是我的代码(导致问题的代码标有#):
from tkinter import*
from random import*
score = 0
Fenetre = Tk()
def Clavier(event):
global coords
global score
global label
touche = event.keysym
if touche == "Up":
coords = (coords[0], coords[1] - 10)
elif touche == "Down":
coords = (coords[0], coords[1] + 10)
elif touche == "Right":
coords = (coords[0] + 10, coords[1])
elif touche == "Left":
coords = (coords[0] -10, coords[1])
canvas.coords(eater, coords[0], coords[1], coords[0]+20, coords[1]+20)
while canvas.bbox(eater) == canvas.bbox(food):
canvas.delete(food)
label.destroy()
global food
up_score = score
up_score = up_score + 1
score = up_score
label = Label(Fenetre, text = up_score) # line 34
label.pack()
X=choice(liste)
Y=choice(liste)
food = canvas.create_rectangle(X,Y,X+20,Y+20,fill="grey")
#fond = PhotoImage(file="Moi.gif")
canvas = Canvas(Fenetre, width=189, height=189)
#canvas.create_image(0,0,image=fond,anchor = NW)
coords = (0, 0)
liste_couleur = ["green","white","red","blue","yellow","violet","orange"]
couleur = choice(liste_couleur)
eater = canvas.create_oval(0,0,20,20,fill=couleur)
canvas.focus_set()
canvas.bind("<Key>", Clavier)
liste = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180]
X = choice(liste)
Y = choice(liste)
food = canvas.create_rectangle(X,Y,X+20,Y+20,fill="grey")
label = Label(Fenetre, text = score) # line 59
label.pack()
canvas.pack()
Fenetre.mainloop()
如果重要的话,我使用的是 Python 3.2。
【问题讨论】:
-
您为什么要销毁标签只是为了重新创建它并尝试将其打包回同一个地方?只更改现有标签的文本会容易得多。
-
由于循环
while,我销毁了一个标签并重新创建了另一个标签。如果我删除我的一个标签,它会因为def而导致类似NameError: name 'up_score' is not defined或NameError: global name 'label' is not defined的错误。它也可能来自我,因为我做错了...... -
我完全不明白那个解释。为什么
while循环意味着您不能只更改现有标签的文本?更改现有标签的文本对删除标签有何影响?
标签: python canvas layout tkinter label