Ruby Tk条目小部件不会更新textvariable

时间:2012-05-29 07:09:00

标签: ruby tk

我正在尝试使用TK为Mad Libs程序在Ruby中编写GUI。本质上,它需要从Entry小部件中获取用户的输入,并用该信息替换一行文本中的某些单词。 以下是相关代码($ content是父窗口):

$name=TkVariable.new()
name=Tk::Tile::Entry.new($content) {width 7; textvariable $name}.grid(:column =>1, :row  =>0, :sticky => 'we')
# Mad Lib base text
$text=TkVariable.new("My name is #{name.get}.")

# Displays end result
def showResult
display=Tk::Tile::Label.new($content) {textvariable $text}.grid(:column =>0, :row     => 6, :sticky => 'we')
end

# Button to replace input in base text.
# Clicking this button adds a new Label widget containing the text. The variables,
#however, retain whatever value they were initialized to (in this case, nothing)
Tk::Tile::Button.new($content) {text 'Submit'; command 'showResult'}.grid(:column => 1,     :row => 5, :sticky => 'we')

据我所知,name.get应该给我任何我在Entry小部件字段中输入的内容。但名字和名字都没有更新。

2 个答案:

答案 0 :(得分:0)

文本变量不能以这种方式工作。看来你正试图将一个textvariable嵌入到另一个textvariable中。当您执行"My name is #{name.get}."时,它会在执行此语句时获得name变量的值,它将不会动态更新。

如果您希望条目小部件和标签保持同步,则需要共享相同的变量。

答案 1 :(得分:0)

不确定但是试试......

def showResult
   $text.value = "My name is #{name.get}."
   display=Tk::Tile::Label.new($content) {textvariable $text}.grid(:column =>0, :row     =>    6, :sticky => 'we')
end

这应该在每次调用showResult时更新变量 但不完全确定条目框

这是我更新我的TkVariables

的方式