ruby - 理解 ruby​​ 中的 Tk 列表框

标签 ruby tk-toolkit

我正在尝试制作一个小程序来将一些数据转换成可用的形式。我希望它做的一件事是能够选择一些文件并对它们执行操作,所以我想我应该使用 Tk 中的列表框对象来做到这一点。我希望能够打开文件并查看其文件名显示在列表框中。据我所知,这正是在列表框中使用 listvariable 的目的。然而,当我运行代码时,列表框永远不会更新(尽管 listvariable 变量中已有的项目显示得很好)。

这里是 MWE 的接近结果。我做错了什么,我误解了什么基本思想?

require 'tk'
require 'tkextlib/tile'

$path_list = []
$populate_list = TkVariable.new( $path_list )

def get_file
  file = Tk.getOpenFile
  file = open(file) unless file.empty?
  path = File.basename(file, ".out")
  if $path_list.include?(path)
    Tk.messageBox(
        'type'    => "ok",
        'icon'    => "warning",
        'title'   => " - Minimum Working Example - ",
        'message' => "This file has already been added! Nothing was added to the list"
    )
  else
    $path_list.push(path)
  end
end

root = TkRoot.new {title "- Minimum Working Example -"}
frame = Tk::Tile::Frame.new(root) {padding "3 3 12 12"}.grid( :sticky => 'nsew') # 'north south east west'
TkGrid.columnconfigure root, 0, :weight => 1; TkGrid.rowconfigure root, 0, :weight => 1

$file_listbox = Tk::Listbox.new(frame) {
  listvariable $populate_list}.grid( :column => 1, :row => 0, :rowspan => 6)

Tk::Tile::Button.new(frame) {
  width 15; text 'Open file...'; command {get_file}}.grid( :column => 0, :row => 1)

Tk.mainloop

我是否需要以其他顺序编写它?

最佳答案

只需添加一行代码:

$populate_list.value = $path_list

在此下:

$path_list.push(path)

它对我有用,尽管看起来很奇怪。

TkVariable 为您的 ruby​​ 变量创建一个代理,从而将您的 ruby​​ var 引用与 Tk 小部件桥接起来。但我不知道为什么代理变量的更改不会影响它指向的变量。我不确定它是否应该自动执行此操作。

关于ruby - 理解 ruby​​ 中的 Tk 列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14676711/

相关文章:

ruby - 在 macOS App 中使用非系统 ruby​​ 执行 ruby​​ 脚本

ruby - 处理测试中预期的失败

添加按钮时 TCL/TK 错误窗口或路径名

c# - .NET 和 TK 之间是否有任何绑定(bind)

python Tix - 如何清除组合框

ruby-on-rails - 动态类别和子类别选择器 [Rails 6]

ruby-on-rails - Net::IMAP 失败:连接已关闭

ruby-on-rails - 将字符串插入 ruby​​ 方法的一部分

tcl - 使用网格时无法将 tcl/tk 程序居中

python - 使用 Tkinter 按钮了解 Python Lambda 行为