如何在 Tkinter 应用程序中嵌入终端?

问题描述 投票:0回答:2

我想在我的 Tkinter 主窗口中嵌入一个终端。我想要一个子窗口,其中可以运行终端(基于 Bash 的终端)。我还希望能够让我的程序与终端交互,至少我想读取当前工作目录和/或设置它。

不知道是不是真的不可能。我过去可以用 Perl/Tk 做到这一点,所以也许可以在这里复制。

我当时使用的代码是这样的:

$frame3=$mw->Frame(-borderwidth=>2, -relief=>'groove', # -label=>'stuff for thought',
                             -labelBackground=>CADRAWWINCOLOR,-background=>CADRAWWINCOLOR);                 

$cv=$frame3->Canvas(-height=>$cvheight,-width=>$cvwidth,-background=>CADRAWWINCOLOR,
                             -bg => CADRAWWINCOLOR,
                             -relief => 'sunken')->pack(-expand => 1, -fill => 'both');
         
# this Frame is needed for including the xterm in Tk::Canvas 
my $xtermContainer = $cv->Frame(-container => 1);
my $xtid = $xtermContainer->id();
# converting the id from HEX to decimal as xterm requires a decimal Id
my ($xtId) = sprintf hex $xtid;
     
my $dcontitem = $cv->createWindow($xtermWidth/2,$xtermHeight/2,
                                       -window => $xtermContainer,
                                       -width => $xtermWidth,
                                       -height => $xtermHeight,
                                       -state => 'normal');
         
system("xterm -into $xtId -fn $fontname -geometry $geometry +sb -bg black -fg white -e ./xtermjob.pl $AAfname 5 &"); 

其中

$mw
是主 Tk 窗口。

当然,我完全同意 Bryan 的观点:虽然我以前从未使用 GUI 库进行过编程,但我的程序(相当大,有点像 wiki)运行得很好,专门用于 GUI 本身的代码量惊人地少。

我尝试翻译此 Perl 代码,但我遇到了 ID 问题。

我唯一找到一些从 Tkinter 中提取 ID 的方法的参考是在 Effbot 中,但是当我使用它时,我得到

'AttributeError: Frame instance has no attribute 'window_id'
,所以一定有问题:

termf = Frame(root)
termf.pack(side=BOTTOM, fill=X)
id=termf.window_id()  
os.system("xterm -into %d -fn -misc-fixed-medium-r-normal--8-80-75-75-c-50-iso10646-1 -geometry 150x150+0+0 +sb -bg black -fg white -e /root/.bashrc &" % id);  
python tkinter terminal
2个回答
37
投票

我很高兴地说,其实是可以做到的,而且只需要几行代码就可以做到(不知道用其他工具包是不是这么简单):

from Tkinter import *
import os

root = Tk()
termf = Frame(root, height=400, width=500)

termf.pack(fill=BOTH, expand=YES)
wid = termf.winfo_id()
os.system('xterm -into %d -geometry 40x20 -sb &' % wid)

root.mainloop()

之前的问题是wid使用了错误的函数。


0
投票

亚历山德罗(Alessandro)已经在他认为合适的模型之前五个小时报告了。对于那些在未来搜索中遇到此项目的人,我将记录更多我所知道的背景事实:

很幸运,Bryan 在这里提请注意 window_id() 和 winfo_id() 之间的差异,并纠正其他人在编写各种工具包时所犯的错误。

我很有趣的是 stackoverflow 与更专业的渠道相比如何。在这种情况下,Tkinter 邮件列表 http://mail.python.org/pipermail/tkinter-discuss/2011-September/002968.html 迅速而准确地回复了该问题。

Tkinter 至少是对某些登月火箭软件的改进。

© www.soinside.com 2019 - 2024. All rights reserved.