使用复选框替换链接到输入框的按钮

时间:2016-02-07 15:19:34

标签: python tkinter

这是我目前用于选择不同选项的代码,并将它们显示在框中(Minecraft ArmorStand Generator)。

from tkinter import *

default = "/summon ArmorStand ~ ~ ~ {CustomNameVisible:1}"

NoAI = ",NoAI:1"
inputbox = Entry()
inputbox.place(x=10,y=10,width=900,height=50)

root = Tk()

def addNOAI():
    inputbox.insert(45, NoAI)

inputbox = Entry()
inputbox.place(x=10,y=10,width=900,height=50)

Button(text="Add NoAI",command=addNOAI,relief = FLAT, bg = "#eF651A", fg = "white", width= 25, height = 2).place(x=10,y=123)
root.title("WIP")
root.wm_state('zoomed')
root.mainloop()

我想要做的是用勾选框替换按钮,以防止多次按下按钮。如果他们单击按钮,添加文本,如果他们取消勾选,将其删除..我不知道从哪里开始,所以任何正确方向的提示都会很好。

1 个答案:

答案 0 :(得分:0)

我有一个有效的解决方案,你可以在下面试试。

from tkinter import *

default = "/summon ArmorStand ~ ~ ~ {CustomNameVisible:1}"

NoAI = ",NoAI:1"
inputbox = Entry()
inputbox.place(x=10,y=10,width=900,height=50)

root = Tk()

def addNOAI():
    state = var.get()

    if state == 1: #if the state is checked
        inputbox.insert(45, NoAI) #then add the text
    else: #if the state is not check
        inputbox.delete(0, 7) #delete the text

inputbox = Entry()
inputbox.place(x=10,y=10,width=900,height=50)

var = IntVar() #sets up variable for check button

c = Checkbutton(text="Add NoAI", command=addNOAI, variable=var) #defining check button variable and command
c.place(x=10,y=123)

root.title("WIP")
root.wm_state('zoomed')

root.mainloop()

目前唯一的问题是,您要删除输入框中的所有内容(更准确地说,从位置0到位置7)。我假设会有多个检查按钮,都将自己的字符串添加到输入框中。

作为一种解决方案,我建议从输入框中提取所有内容,找到所需的字符串,将其取出,然后重新放入所有内容。这是一个例子。

def addNOAI():
    state = var.get()

    if state == 1: #if the state is checked
        inputbox.insert(45, NoAI) #then add the text
    else: #if the state is not check
        contents = inputbox.get() #gets all of contents

        position = contents.find(NoAI) #finds the first position of desired string to remove

        newcontents = contents[:position]+contents[position+7:] #gets string before the word, and after the word, and joins them

        inputbox.delete(0, 'end') #clears input box for new entry

        inputbox.insert(45, newcontents) #re-inserts the string

这里,当用户取消选中该框时,程序会在输入框的内容中找到该字符串的起始位置。因为您知道字符串的长度(在本例中为7),您可以从输入框的当前内容中删除字符串,并将其放在一个新变量中。现在你有一个新的字符串,没有未选中的字符串,你可以清除输入框,并将新的字符串放入。

希望这有帮助!

相关问题