2016-01-23 70 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