gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:50:10 25 4
gpt4 key购买 nike

我正在尝试编写一个小程序来将一些数据转换成可用的形式。我希望它做的一件事是能够选择一些文件并对它们执行操作,所以我想我会使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com