【问题标题】:Is it possible to use unicode characters with ruby/tk?是否可以在 ruby​​/tk 中使用 unicode 字符?
【发布时间】:2012-02-02 12:53:09
【问题描述】:

我在带有 Tk 接口的 Windows 7 上使用 Ruby 1.9.3。在下面的简单示例中,如果我单击一个按钮,GUI 将返回一个“??????”字符串而不是显示的“привет”。是否可以取回输入的实际 unicode 字符串?

#!/usr/bin/env ruby
# coding:utf-8 vi:et:ts=2
require 'tk'
TkRoot.new.tap { |o|
  $edit = TkEntry.new( o ).tap { |o|
    o.pack( :side => 'left' )
    o.insert( 0, "привет" )
  }
  TkButton.new( o, :text => "click me" ).tap { |o|
    o.pack( :side => 'left' )
    o.bind( '1' ) {
      ##  In this place i want unicode, but got garbage :(
      puts( $edit.get().encoding.name )
      puts( $edit.get().inspect )
    }
  }
  o.mainloop()
}

【问题讨论】:

    标签: ruby windows unicode tk


    【解决方案1】:

    所以我检查了 Windows 并让它工作。我建议你把它放在文件的顶部:

    #!/usr/bin/env ruby -Ku
    require 'tk'
    # etc.
    

    # coding 位是不必要的; -Ku 标志告诉 Ruby 使用 Unicode 代码页。虽然我在 Mac 上的测试似乎没有这个问题(附加 -Ku 或使用 # coding: utf-8 都可以),但它确实发生在 Windows 中。我正在运行与您相同的版本,只是在 Parallels 中。

    或者,您可以删除 shebang 部分并使用 ruby -Ku test.rb 运行文件

    原答案:
    是的,虽然我习惯的解决方案是使用 UTF-8。您只需将# coding: utf-8 放在文件的第一行,Ruby 就会神秘地切换到以 UTF-8 处理字符串:

    # coding: utf-8
    require 'tk'
    TkRoot.new.tap { |o|
    # etc.
    

    为了进一步阅读,我建议this link 了解 Ruby 对编码的看法。

    【讨论】:

    • 不幸的是,我的文件已经有相应的 shebang :(。否则,其中的非 ascii 文本“привет”字符串处理不正确。我已修改我的问题以反映这一点。跨度>
    • @EyeofHell 好的,我刚刚检查了我的 Windows 安装。 Windows Ruby 确实对编码更挑剔,但在文件顶部使用#!/usr/bin/env ruby -Ku 很容易解决。
    • 澄清:Tk 本身对所有平台上的 Unicode 都非常满意,但是 Ruby 必须正确告知源文件的编码是什么,以便理解其中的字符.
    【解决方案2】:

    如果您希望避免 -Ku 'hack',您必须指定 UTF-8 编码,不仅在您自己的 Ruby 源文件中,而且还通过某种方式告诉 Tk。 (Ruby 的 Tk 包装器当然有自己的源文件。)

    我稍微修改了您的程序(并注意到了更改)。现在它适用于 Windows 7,使用 Ruby 2.2.5(包括 Tk 8.5.12):

    #!/usr/bin/env ruby
    # coding:utf-8 vi:et:ts=2
    require 'tk'
    Tk::Encoding.encoding = ''.encoding  # Tell Tk which encoding to use (I added this line).
    TkRoot.new.tap { |o|
      $edit = TkEntry.new( o ).tap { |o|
        o.pack( :side => 'left' )
        o.insert( 0, "привет" )
      }
      TkButton.new( o, :text => "click me" ).tap { |o|
        o.pack( :side => 'left' )
        o.bind( '1' ) {
          ##  In this place i want unicode, but got garbage :(
          puts( $edit.get().encoding.name )
          puts( $edit.get().inspect )
          puts( $edit.get() )  # See the result (I added this line).
        }
      }
      o.mainloop()
    }
    

    在控制台上,我得到的结果是:

    UTF-8
    "\u043F\u0440\u0438\u0432\u0435\u0442"
    привет
    

    【讨论】:

      猜你喜欢
      • 2014-03-20
      • 2010-12-12
      • 2011-10-24
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 2022-05-31
      • 1970-01-01
      • 2016-10-04
      相关资源
      最近更新 更多