使用 linux 终端修改 python var



我使用 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')

命名管道旨在允许许多程序写入它们,但只有一个程序应读出数据。

最新更新