首页 > 解决方案 > 将坐标写入 .txt 文件以供将来在程序中使用

问题描述

我创建的代码在单击后显示我单击的坐标,我的问题是将这个东西附加到名为 coord.txt 的 txt 文件中,代码是:

from pynput import mouse

def on_click(x, y, button, pressed):
    c=open("coord.txt", "w+")
    if button == mouse.Button.left:
        print(x, y)
        c.write(x)
        c.write(y)
        return False
    c.flush()
listener = mouse.Listener(on_click=on_click)
listener.start()
listener.join()

错误是:

TypeError: write() argument must be str, not int

但我尝试没有任何帮助。将来我想将此 def 与我在 pyqt5 gui 中的所有工具按钮配对,如下所示: https ://github.com/spokom/mycodes/tree/master

标签: pythonfile

解决方案


您需要将xand转换y为字符串才能编写它们。

此外,您应该用分隔符将它们分开,否则当您尝试读回它们时,您只会得到一个数字。

def on_click(x, y, button, pressed):
    with open("coord.txt", "w") as c:
        if button == mouse.Button.left:
            print(x, y)
            c.write(str(x) + "\n")
            c.write(str(y) + "\n")
            return False

无需+在打开模式下使用修饰符。您只是在写入文件,而不是从中读取。


推荐阅读