2016-01-23 69 views
1

我正在從一個Pi2Go機器人開始一個小項目,它將從超聲波傳感器獲取數據,然後放置一個X,如果它看到的是一個物體,並且它現在在哪裏,我有兩個問題: 如何在tkinter上設置座標位置?例如,我想在0,0或120,120插入文本。Tkinter - 座標

其他: 我如何讓tkinter不斷更新我正在建造的地圖 乾杯!

+1

要放置小部件按座標查看['place'](http://effbot.org/tkinterbook/place.htm)幾何管理器。您可以嘗試在給定的座標上放置所需字母的標籤小部件。由於這可能會變得有點醜陋和不合格,你可能會考慮一種完全不同的方法,例如, Pygame(應該能夠解決你的任務,但我從來沒有使用它)。對我來說,這看起來不僅僅是一個遊戲,而不是一個GUI任務來解決,因爲它或多或少是動態呈現對象。然而,如果你提供了一些樣本座標,我可以嘗試一下,如果你仍然卡住... – albert

+0

你可以使用'root.after()'來經常調用函數並更新映射 - 參見:http:// stackoverflow .com/a/34940146/1832058 – furas

+0

@albert讓我們假設120,120 90,90 30,30並在所有em上放置X –

回答

1

我剛剛拼湊了一些代碼,以簡要介紹如何使用place幾何管理器。爲了進一步的說明,請參閱代碼中的註釋:

#!/usr/bin/env python3 
# coding: utf-8 

from tkinter import * 


# init our application's root window 
root = Tk() 
root.geometry('480x480') 


# let's provide same sample coordinates with the desired text as tuples in a list 
coords = [(30,30,'X'), (90,90,'X'), (120,120,'X'), (240,240,'X'), (270,270,'X'), (360,360,'O')] 


# interate through the coords list and read the coordinates and the text of each tuple 
for c in coords: 
    l = Label(root, text=c[2]) 
    l.place(x=c[0], y=c[1]) 


# start a loop over the application 
root.mainloop() 

我如果您使用Python 2使用Python 3,您需要更改tkinterTkinter。如果你需要將我的代碼移植到Python 2,那應該會有訣竅。

1

使用.place函數。

就像你可以做以下

label = Label(root, text = 'i am placed') 
#places the label in the following x and y coordinates 
label.place(20,20) 
0
from tkinter import * 
from PIL import Image, ImageTk 

class buildWorld: 
    def __init__(self, root): 
     self.canvas = Canvas(root, width=1000, height=800) 

     self.canvas.pack() 
     self.tmp = Image.new('RGBA', (1000,800), color=(0,0,0)) 
     self.img = ImageTk.PhotoImage(image=self.tmp) 
     self.Land = self.canvas.create_image(0, 0, anchor='nw', image=self.img) 

     self.tmp = Image.new('RGBA', (50, 50), color=(255, 0, 0)) 
     self.img1 = ImageTk.PhotoImage(image=self.tmp) 
     self.mob1 = self.canvas.create_image(125, 125, anchor='nw', image=self.img1) 


     self.tmp = Image.new('RGBA', (50, 50), color=(0, 255, 0)) 
     self.img2 = ImageTk.PhotoImage(image=self.tmp) 
     self.mob2 = self.canvas.create_image(300, 300, anchor='nw', image=self.img2) 

root = Tk() 
world = buildWorld(root) 
mainloop() 
0

最好的辦法是使用你的X和Y座標的place方法絲毫參數。

label = Label(root, text = 'Placed On X and Y') 
label.place(x= X,y = Y) 

或另一種方式是使用pack方法,將採取類似的論點:

label.pack(padx = W,pady = H) 

其中W和H是從中心點的距離,以你的座標X和Y