我是红宝石的新手。有没有办法缩短这段代码("增量var#")? 我创建了26个字母表条目。
require 'tk'
dis = { 'padx' =>5, 'pady' =>5}
root = TkRoot.new {title "Alphabet"}
elpar = {'height' => 25, 'width' => 25}
f1 = TkFrame.new{
relief 'sunken'
borderwidth 1
background "black"
height 800
width 800
dis
pack
}
f1.place('x' => 0, 'y' => 0)
el00 = TkEntry.new(f1)
el01 = TkEntry.new(f1)
el02 = TkEntry.new(f1)
to # Can I use loop here to shorten it?
el26 = TkEntry.new(f1)
var1 = TkVariable.new
to #(1)
var2 = TkVariable.new
el00.textvariable = var1
var1.value = "A"
el00.place(elpar)
el00.place('x' => 0, 'y' => 0)
to #
el26.textvariable = var26
var26.value = "Z"
el26.place(elpar)
el26.place('x' => 728, 'y' => 0)
Tk.mainloop
(1)我尝试过使用循环
x = 1
while x < 27
"var#{x}"=TkVariable.new # var1 is still undefined local variable if I use a loop.
"var" + x.to_s=TkVariable.new # another variation that i've tried
x += 1
end
有没有办法缩短它?我的代码只是1的增量?
谢谢, 吉姆
答案 0 :(得分:1)
您可以将条目存储在数组中:
entries = Array.new(26) { TkEntry.new(f1) }
然后阅读您的参赛作品:
entries[0] #=> first entry
entries[1] #=> second entry
使用A到Z的字符范围设置参数:
('A'..'Z').each_with_index do |character, index|
variable = TkVariable.new
variable.value = character
entries[index].textvariable = variable
entries[index].place(elpar)
entries[index].place('x' => 0, 'y' => 0) # you did not explain how to calculate this
end