我使用Python编写了一些基本的Tkinter文本标签,但是我想使用Linux终端中的命令修改标签中的文本。
这是我的代码:

#! /usr/bin/python
from tkinter import *
outputText = 'Libre'

root = Tk()

w = 70
h = 50

ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()

x = (ws/10) - (w/5)
y = (hs/5) - (h/5)

root.geometry('%dx%d+%d+%d' % (w,h,x,y))

root.overrideredirect(1)

var = StringVar()

l = Label(root, textvariable=var)
l.pack()
l.place(x=10, y=10)

var.set(outputText)

root.mainloop()

最佳答案

有很多方法。我首先想到的是一个命名管道(又名fifo)。下面是python代码(我假设python3是由于您的tkinter导入,即使您的shebang是针对python2的):

#!/usr/bin/env python3

import tkinter as tk
import os
import stat
from threading import Thread

class FIFO(Thread):
    def __init__(self, pipename, func):
        self.pipename = pipename
        if pipename in os.listdir('.'):
            if not stat.S_ISFIFO(os.stat(self.pipename).st_mode):
                raise ValueError("file exists but is not a pipe")
        else:
            os.mkfifo(pipename)
        Thread.__init__(self)
        self.func = func

        self.daemon = True
        self.start()

    def run(self):
        while True:
            with open(self.pipename) as f: # blocks
                self.func(f.read())

    def close(self):
        os.remove(self.pipename)

root = tk.Tk()
var = tk.StringVar(value='Libre')

# pipes the content of the named pipe "signal" to the function "var.set"
pipe = FIFO("signal", var.set)

l = tk.Label(root, textvariable=var)
l.pack(fill=tk.BOTH, expand=True)
root.geometry("200x100")
root.mainloop()
pipe.close()

本例创建了一个名为“signal”的管道,因此您写入该管道的任何内容都将在变量中设置。例如,如果在同一文件夹中打开一个新终端并键入
echo I am a cucumber > signal

然后tkinter窗口中的标签变为“我是黄瓜”。
您也可以从任何其他程序或编程语言访问它。例如,如果要从另一个python程序发送数据:
with open('signal', 'w') as f:
    f.write('I am a banana')

命名管道的设计允许许多程序向其写入数据,但只有一个程序应读取数据。

10-05 20:28
查看更多