如何在执行时永久更改程序数据?

时间:2015-04-24 00:19:50

标签: python user-interface python-3.x tkinter tk

我写了一个小程序,它允许我在画布小部件中移动一个矩形。我计划扩展程序,允许我在屏幕上移动其他小部件,这样我就可以更轻松地移动窗口中的内容,即通过拖放移动项目,而不是指定直接坐标(至少不明确)。

以下是目前的代码:

来自tkinter import *     root = Tk()

class Move_Shape:
    data = {'x': 0, 'y': 0}
    canvas = Canvas(width = root.winfo_screenwidth(), height = root.winfo_screenheight())


    def __init__(self, shape, fill = 'White', *coords):
        shape_coords = open('Shape_coords.py', 'r')
        new_coords = shape_coords.readline()[1:-1]
        new_coords = (new_coords).split(',')

        if coords != (): new_coords = coords

        if shape == 'line': 
            tag = 'line'
            self.canvas.create_line(coords, tags = tag, fill = fill)

        elif shape == 'rectangle': 
            tag = 'rect'
            self.canvas.create_rectangle(coords, tags = tag, fill = fill)
        ... More Code


        self.canvas.tag_bind(tag, '<Button-1>', self.click)
        self.canvas.tag_bind(tag, '<Button1-Motion>', self.track)
        self.canvas.tag_bind(tag, '<ButtonRelease-1>', self.release)
        self.canvas.grid()


    def click(self, event):
        self.data.update({'x': event.x, 'y': event.y})
        self.item = self.canvas.find_closest(self.data['x'], self.data['y'])

    def track(self, event):
        x, y = event.x - self.data['x'], event.y - self.data['y']
        self.canvas.move(self.item, x, y)
        self.data.update({'x': event.x, 'y': event.y})

    def release(self, event):
        self.data.update({'x': event.x, 'y': event.y})
        shape_coords = open('shape_coords.py', 'w')
        coords = str(self.canvas.coords(self.item))
        shape_coords.write(coords)
        shape_coords.close()

label = Label(text = 'text more text some more text', fg = 'white', bg = 'white')

Move_Shape('rectangle', 'blue', 50, 50, 200, 200)
Move_Shape( 'oval', 'green', 50,50,200,200)
Move_Shape( 'arc', 'red', 50,50,200,200)



mainloop()

所以现在我可以在屏幕上的任何位置移动矩形。但是,当我重新打开窗口时,矩形从它的初始位置开始,尽管这是预期的结果。尽管它可以保持矩形在被拖动的位置被丢弃时所需的结果。

一个这样的解决方案,我可以想到它写入(和重写)到另一个文件,以便新的coords重写文件中的原始coords,虽然对我来说这看起来很乱,因为我必须创建一个全新的文件。是否有更清洁,更优雅的方法来实现这一目标,或者我是否应该将新的坐标添加到文件中?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您需要决定的关键是:这些数据的范围是什么?

是吗:

  • 属于程序本身
  • 的数据
  • 属于当前计算机
  • 的数据
  • 属于当前用户
  • 的数据
  • 别的什么?

如果数据属于当前用户,则修改程序本身是没有意义的。

最有可能的是,将数据写入其他地方(或者可能是数据库)的文件是更好的解决方案。

相关问题