Tkinter条目获取unicode内容

2024-10-03 02:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试从Tkinter条目获取一些值时遇到了一个奇怪的问题。基本上,如果在条目中我没有ascii值并使用get()内容,有时我有一个正确的unicode字符串,有时我有一个ascii字符串a-la unicode而没有规范的'u'。这里是我的代码:

def create():
    try:
        cols = []
        values = []                
        for name in names:
            if (pk <> name):
                if (name in fk_columns):
                    cols.append(name)
                    values.append(box[name].get())
                else:                        
                    cols.append(name)
                    values.append(entry[name].get())                        
        print values                        
        dbutils.create(mDBname, mTable,cols,values)
        frame.master.destroy()
        tkMessageBox.showinfo("New record", "Record created") 
        scrolled_view(root,mDBname,mTable,'g',0, editable)           
    except Exception, err:
        tkMessageBox.showerror("Error", err)           

def update():
    try:
        cols = []
        new_values = []
        old_values = []
        i = 0
        for name in names:
            if (name in fk_columns):
                cols.append(name)
                new_values.append(box[name].get())
            else:                        
                cols.append(name)                    
                new_values.append(entry[name].get())                                       
            if rows[record][i] == None:
                old_values.append('')
            else:
                old_values.append(rows[record][i]) 
            i = i + 1
        print new_values 
        dbutils.update(mDBname, mTable, cols, new_values, old_values)
        frame.master.destroy()
        tkMessageBox.showinfo("Update", "Record updated")
        scrolled_view(root,mDBname,mTable,'g',0, editable)            
    except Exception, err:
        tkMessageBox.showerror("Error", err) 

所以问题是,如果我使用“create”函数,并且我有一个值为“John cana”的条目,当我在shell中打印值时(注意调用dbutils之前的“print values”),我得到:

^{pr2}$

而且该函数工作正常。在

当我使用update函数时,即使只更新第二个值而不是python shell上带有“John Can a”的值(在调用dbutils之前调用print new_values),我都得到了:

['17', 'John Can\xe0', 'Marketing']

字符串“John Can\xe0”没有“u”。这最终产生了经典的错误“ordinal not in range 128”。我的问题是为什么一样入口.get()呼叫产生这种不同的行为以及如何解决它。提前谢谢!在


Tags: nameinnewgetifolderrvalues
2条回答

问题是由于sqlalchemy原始查询造成的:当我创建记录(插入)时,条目正确地将文本处理为unicode(无纯字符串):

u'John Can\xe0'

当基本上更新时,我做一个原始选择(通过sqlalchemy)来填充条目和值

^{pr2}$

来自原始精选。添加

'?charset=utf8' 

连接字符串解决了这个问题。 唯一不能解释的是为什么Tkinter条目正确处理“John Can\xe0”而不引发错误。顺便说一句,现在代码生效了!在

我不知道到底是不是你要找的,我向你展示迄今为止测试过的行为:

>>> name = u'John Can\xe0'
>>> name = bytes(name,"unicode_escape")
>>> name.decode('unicode_escape')
'John Canà' # This is the output

因此,为了避免在字符串中出现\xe0,请在显示任何字符串之前进行转换

相关问题 更多 >