当传递一个包含嵌入空格的字符串的元组时,easygui为什么要插入花括号?

2024-10-01 04:55:38 发布

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

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))

Tags: thetoselfinfooutputagegenderpay
1条回答
网友
1楼 · 发布于 2024-10-01 04:55:38

如何解决这个问题?你知道吗

easygui.msgbox假设它的msg是一个字符串,就像'Hello',但是你给它传递了一个元组,一个像 'age', 32, 'salary', 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是一个字符串,但在将msg传递给创建GUI元素的代码之前,实际上并不检查这是否为真。碰巧,默认的GUI提供者是Python的tkinter包,而tkinter最终依赖于用另一种语言tcl编写的代码在屏幕上呈现GUI元素。你知道吗

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

'Age: ', 32, 'years old \nPay:', 30000

tcl需要能够识别组成'years old \nPay:'的三个字符串属于同一个字符串。在tcl中实现这一点的方法是用花括号包装(或“引用”)字符串。这就是为什么在传递output元组时会看到消息框中的花括号。你知道吗

相关问题 更多 >