Skip to main content
 首页 » 编程设计

python之为什么 easygui 在传递包含带嵌入空格的字符串的元组时插入大括号

2024年12月31日31lvdongjie

当我们试图打断文本时,Easygui 会插入大括号。有没有办法在不提供大括号的情况下打断文本。

import easygui 
 
#Class for seperating workers. 
class HumanClassification: 
    #Sets the default worker info to null: 
    def __init__(self): 
        self.age = 0 
        self.pay = 0 
        self.gender = '' 
 
    #Outputs the workers info: 
    def classification(self, age, pay, gender): 
        self.age = age 
        self.pay = pay 
        self.gender = gender 
 
 
 
#Current Workers: 
myListWorkers = ['Bob', 'Diann', 'Tec'] 
Bob = HumanClassification() 
Diann = HumanClassification() 
Tec = HumanClassification() 
 
 
 
#Instantize Classes: 
Bob.classification(42, 15000, 'male') 
Diann.classification(25, 1000, 'female') 
Tec.classification(18, 200000, 'male') 
 
#Asks user if he/she wants to find info about worker: 
bossInput = easygui.buttonbox("Who do you want to view info on? ", choices=myListWorkers) 
bossInputNew = eval(bossInput) 
 
output = 'Age:', bossInputNew.age, 'years','old \n',  'Pay:', bossInputNew.pay, 'dollars', 'Gender:', bossInputNew.gender 
#Prints out the output from code: 
easygui.msgbox(msg=(output)) 

请您参考如下方法:

如何解决这个问题?

easygui.msgbox 假设它的 msg 是一个 string,比如 'Hello',但是你是向它传递一个 元组,一个对象序列,例如 '年龄', 32, '薪水', 30000.

您可以通过将字符串传递给 easygui.msgbox 来解决这个问题。您的输出是一个带有嵌入式变量值的字符串,因此这是使用 format string 的好例子.格式字符串是包含占位符(通常是大括号对 {})的字符串,您可以将其替换为变量值。

改变这一行:

output = 'Age:', bossInputNew.age, 'years','old \n',  'Pay:', bossInputNew.pay, 'dollars', 'Gender:', bossInputNew.gender 

到:

output = 'Age: {} years old \nPay: {} dollars Gender:{}'.format(bossInputNew.age, bossInputNew.pay, bossInputNew.gender) 

它应该可以工作。

为什么会这样?

easygui.msgbox 假设它的 msg 是一个 string,但是在传递 之前实际上并没有检查这是真的msg 到创建 GUI 元素的代码。碰巧的是,默认的 GUI 提供程序是 Python 的 tkinter 包,而 tkinter 最终依赖于用另一种语言 tcl 编写的代码来在屏幕上呈现 GUI 元素。

tcl 通常将所有变量都视为字符串。给定一个元组

'Age:', 32, '岁\nPay:', 30000

tcl 需要能够识别组成 'years old\nPay:' 的三个字符串属于一起。在 tcl 中执行此操作的方法是用大括号包裹(或“引用”)字符串。这就是为什么当您将 output 元组传递给消息框时,您会在消息框中看到花括号。