文本值不适合按钮

问题描述 投票:0回答:1

这是一个与 tkinter 模块相关的问题

就像在我的代码中一样,有一个名为

optButton1
的变量,我已经制作了它并使用了此代码示例 -

Button(bottomFrame, text=firstOption[0], font=("arial", 18, "bold"), bg="black", fg="white", bd="0", activebackground="black", activeforeground="white", cursor="hand2")

在文本属性中,我插入了一个名为

firstOption
的第一个索引的变量和一些其他属性。(
firstOption[0]
的值是
"Crab"
,这是一个小单词,适合
firstOption
的按钮)

当我运行代码时,会出现一个 GUI,其中会出现该按钮,如果我单击它将更改选项的值,或者我应该简单地说

optButton1
的文本值更改为
firstOption[1]
,即:

optButton1.config(text=firstOption[1])

text=firstOption[1]
的值是
"Doctor of Principal"
,所以它对于我的按钮大小来说太长了,但问题是我不想更改该按钮的大小,所以它不适合并且整个文本不可见在按钮上。

我尝试在

wrap="word"
中使用属性
optButton1
,即:

optButton1 = Button(bottomFrame, text=firstOption[0], wrap="word",font=("arial", 18, "bold"), bg="black", fg="white", bd="0", activebackground="black", activeforeground="white", cursor="hand2")

现在,如果我运行上面的代码行,则会抛出错误!

请帮助我这是一个非常重要的项目请!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

from tkinter import *

def select(event):      # Function to set what happens after the option buttons are clicked
    b = event.widget
    value = b["text"]
    if value == correctAns[0]: #if correct answer chosen
        questionArea.delete(1.0, END)   #deletes everthing in Question Area
        questionArea.insert(END, questions[1])  #new question appears
        
        optButton1.config(text=firstOption[1])  #new options appear
        optButton2.config(text=secondOption[1])
        optButton3.config(text=thirdOption[1])
        optButton4.config(text=fourthOption[1])

#Question and options and correct options

correctAns = ["Chinkara", "Doctor of Philosophy", "Desert",
              "Sep 8", "Prayag. Haridwar, Ujjain, Nasik", 

              "MRTPC", "1,2 and3", "Free on Board",
              "the world's first hospital on rails operating in India.","Haryana",
              
              "Bharathatyarn", "Veena", "Uttar Pradesh",
              "Sangeet Academy", "New Delhi"]

questions = ["Which of these animals does not live in the sea?",
             "What is the meaning of education degree, P.H.D?",
             "What type of region is Cholistan, located in Pakistan?",
             "The International Literacy Day is observed on",
             "In which group of places the Kumbha Mela is held every twelve years?",
             
             "The BVO (Brominated Vegetable Oil) was banned in soft drinks by which of the following organisations?",
             "Which of the following is/are youth organisations?\t1. NCC 2. NSS 3. NYK",
             "The abbreviation 'fob' stands for",
             "The Lifeline Express is",
             "Which of the following was the first Indian state to issue photo identity cards to its voters?",
            
             "Thillana is a format of",
             "Most 'ancient musical' instrument among the following is",
             "Of which of the following states is Nautanki, a folk dance?",
             "Which of the following Academy is responsible for fostering the development of dance, drama and music in India?",
             "The headquarters of the Sahitya Academy is at"]

firstOption = ["Crab","Doctor of Principal",
               "River","Sep 8",
               "Ujjain. Purl; Prayag. Haridwar","I.S.I.",
               "1 only","Free on Board",
               "a de-addiction programme to save drug addicts.","Tamil Nadu",
               "Kuchipudi","Sarod",
               "Uttar Pradesh","Lalit Kala Academy",
               "Mumbai"]

secondOption = ["Lobster","Doctor of Philosophy",
                "Mountain","Nov 28",
                "Prayag. Haridwar, Ujjain,. Nasik","AGMARK",
                "2 only","Free of Bargain",
                "the world's first hospital on rails operating in India.","Rajasthan",
                "Odissi","Tabla",
                "Arunachal Pradesh","Sahitya Academy",
                "Chennai"]

thirdOption = ["Shrimp","Doctor of Physiology",
               "Desert","May 2",
               "Rameshwaram. Purl, Badrinath. Dwarika","MRTPC",
               "1 and 2","Fellow of Britain",
               "a popular health magazine founded by Ramoath Goenka.","West Bengal",
               "Bharathatyarn","Sitar",
               "Meghalaya","National School of Drama",
               "New Delhi"]

fourthOption = ["Chinkara","Doctor of Phsychology",
                "Lake","Sep 22",
                "Chittakoot, Ujjain, Prayag,'Haridwar","None of These",
                "1,2 and3","None of these",
                "A health show","Haryana",
                "Kathak","Veena",
                "Orissa","Sangeet Academy",
                "Kolkata"]

root = Tk()
# Window Customization
root.geometry("1272x652+0+0")
root.title("Kaun Banega Crorepati created by Arnav Kumar")
root.config(bg = "black")

#Frames
leftFrame = Frame(root, bg="black", padx=90)
leftFrame.grid(row=0, column=0)

topFrame = Frame(leftFrame, bg="black", pady=15)
topFrame.grid()

middleFrame = Frame(leftFrame, bg="black", pady=15)
middleFrame.grid(row=1, column=0)

bottomFrame = Frame(leftFrame)
bottomFrame.grid(row=2, column=0)

rightFrame = Frame(root, pady=25, padx=50, bg="black")
rightFrame.grid(row=0, column=1)

#Images and label simply designing
img50 = PhotoImage(file="50-50.png")
lifeLine50Button = Button(topFrame, image=img50, bg="black", bd=0, activebackground="black", width=180, height=80)
lifeLine50Button.grid(row=0, column=0)

audiencePoll = PhotoImage(file="audiencePole.png")
audiencePollButton = Button(topFrame, image=audiencePoll, bg="black", bd=0, activebackground="black", width=180, height=80)
audiencePollButton.grid(row=0, column=1)

phoneImg = PhotoImage(file="phoneAFriend.png")
phoneLifelineButton = Button(topFrame, image=phoneImg, bg="black", bd=0, activebackground="black", width=180, height=80)
phoneLifelineButton.grid(row=0, column=2)

centerImg = PhotoImage(file="center.png")
logoLabel = Label(middleFrame, image=centerImg, bg="black", width=300, height=200)
logoLabel.grid(row=0, column=0)

amountImg = PhotoImage(file="Picture0.png")
amountLabel = Label(rightFrame, image=amountImg, bg="black")
amountLabel.grid(row=0, column=0)

layoutImg = PhotoImage(file="lay.png")
layoutLabel = Label(bottomFrame, image=layoutImg, bg="black")
layoutLabel.grid(row=0, column=0)

#question box
questionArea = Text(bottomFrame, font=("arial", 18, "bold"), width=34, height=2, wrap="word", bg="black", fg="white", bd = 0)
questionArea.place(x=70, y=10)

questionArea.insert(END,questions[0])   #inserting questions in question area

labelA = Label(bottomFrame, text="A:", font=("arial", 16, "bold"), bg="black", fg="white", bd = 0)  #Labels of Options i.e. "A:","B:","C","D" 
labelA.place(x=60, y=110)
optButton1 = Button(bottomFrame, text=firstOption[0], font=("arial", 18, "bold"), bg="black", fg="white", bd="0", activebackground="black", activeforeground="white", cursor="hand2", wrap="word")   #Option Buttons formation
optButton1.place(x=100,y=100)

labelB = Label(bottomFrame, text="B:", font=("arial", 16, "bold"), bg="black", fg="white", bd = 0)  #Labels of Options i.e. "A:","B:","C","D"
labelB.place(x=332, y=110)
optButton2 = Button(bottomFrame, text=secondOption[0], font=("arial", 18, "bold"), bg="black", fg="white", bd="0", activebackground="black", activeforeground="white", cursor="hand2")  #Option Buttons formation
optButton2.place(x=370,y=100)

labelC = Label(bottomFrame, text="C:", font=("arial", 16, "bold"), bg="black", fg="white", bd = 0)  #Labels of Options i.e. "A:","B:","C","D"
labelC.place(x=60, y=190)
optButton3 = Button(bottomFrame, text=thirdOption[0], font=("arial", 18, "bold"), bg="black", fg="white", bd="0", activebackground="black", activeforeground="white", cursor="hand2")   #Option Buttons formation
optButton3.place(x=100,y=180)

labelD = Label(bottomFrame, text="D:", font=("arial", 16, "bold"), bg="black", fg="white", bd = 0)  #Labels of Options i.e. "A:","B:","C","D"
labelD.place(x=332, y=190)
optButton4 = Button(bottomFrame, text=fourthOption[0], font=("arial", 18, "bold"), bg="black", fg="white", bd="0", activebackground="black", activeforeground="white", cursor="hand2")  #Option Buttons formation
optButton4.place(x=370,y=180)

#Setting the functionality of Option Buttons
optButton1.bind("<Button-1>", select)
optButton2.bind("<Button-1>", select)
optButton3.bind("<Button-1>", select)
optButton4.bind("<Button-1>", select)

root.mainloop()

如果你想要完整的代码↑

python tkinter button syntax-error word-wrap
1个回答
0
投票

冒着回答不好的问题的风险,这里有一个可能的解决方案,使用内置的

textwrap
模块

注意:由于没有提供真实的示例,我不得不在这里采取一些自由行动 - 您需要将其调整为您的代码

 """Basic example app showing button text wrapping via `textwrap`"""
import tkinter as tk
from textwrap import wrap


root = tk.Tk()
root.geometry('400x400')

optButton1 = tk.Button(
    root, 
    text='Doctor of Principal',
    font=('Arial', 18, 'bold'),
)

# get the text from the button widget
btn_text = optButton1.cget('text')
# set the desired wrap length (in characters)
max_len = 10
if len(btn_text) >= max_len:
    # wrap the text if it's longer than the maximum desired length
    btn_text = '\n'.join(wrap(btn_text, max_len))
    optButton1.config(text=btn_text)

optButton1.pack()


if __name__ == '__main__':
    root.mainloop()

您可以将文本换行代码放入像这样的函数中

def wrap_btn_text(event):
    btn = event.widget
    btn_text = btn.cget('text')
    max_len = 10
    if len(btn_text) >= max_len:
        # wrap the text if it's longer than the maximum desired length
        btn_text = '\n'.join(wrap(btn_text, max_len))
        btn.config(text=btn_text)

然后将其绑定到按钮的

'<Configure>'
,以便在修改按钮时根据需要换行文本

optButton1.bind('<Configure>', wrap_btn_text)

以下是整个事情:

import tkinter as tk
from textwrap import wrap


def wrap_btn_text(event):
    btn = event.widget
    btn_text = btn.cget('text')
    max_len = 10
    if len(btn_text) >= max_len:
        # wrap the text if it's longer than the maximum desired length
        btn_text = '\n'.join(wrap(btn_text, max_len))
        btn.config(text=btn_text)


root = tk.Tk()
root.geometry('400x400')

optButton1 = tk.Button(
    root, 
    text='Doctor of Principal',
    font=('Arial', 18, 'bold'),
)
optButton1.pack()
optButton1.bind('<Configure>', wrap_btn_text)

# here's an example of an update that will trigger the text wrap callback
optButton1.config(text='Especially Long Button Text')
# the callback will also trigger if you set the text from a `textvariable`


if __name__ == '__main__':
    root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.