简体   繁体   English

使用元组单击tkinter中的值更改按钮上的标签文本

[英]Change label text on button using values from tuple click tkinter

I have a list of strings sorted in a tuple like this: 我有一个在元组中排序的字符串列表,如下所示:

values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')

My simple code is: 我的简单代码是:

from tkinter import *

root = Tk()
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')

ru = Button(root,
            text="Next",
            )
ru.grid(column=0,row=0)

lab = Label(root,
            text=values[0])
lab.grid(column=1,row=0)

ru2 = Button(root,
             text="Previous"
             )
ru2.grid(column=2,row=0)

root.mainloop()

I have two tkinter buttons "next" and "previous", the text value of the Label is directly taken from the tuple ( text=value[0] ), however I would want to know how to show the next string from the tuple when the next button is pressed, and how to change it to the previous values when the "previous" button is pressed. 我有两个tkinter按钮“ next”和“ previous”,Label的text值直接取自元组( text=value[0] ),但是我想知道如何显示元组中的下一个字符串按下下一个按钮,以及按下“上一个”按钮时如何将其更改为上一个值。 I know it can be done using for-loop but I cannot figure out how to implement that. 我知道可以使用for循环完成此操作,但是我无法弄清楚如何实现。 I am new to python. 我是python的新手。

Use Button(..., command=callback) to assign function which will change text in label lab["text"] = "new text" 使用Button(..., command=callback)分配将更改标签lab["text"] = "new text"文本的函数

callback means function name without () callback表示不带()函数名称

You will have to use global inside function to inform function to assign current += 1 to external variable, not search local one. 您将必须使用global内部function来通知函数将current += 1分配给外部变量,而不是搜索局部变量。

import tkinter as tk

# --- functions ---

def set_next():
    global current

    if current < len(values)-1:
        current += 1
        lab["text"] = values[current]

def set_prev():
    global current

    if current > 0:
        current -= 1
        lab["text"] = values[current]

# --- main ---

values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
current = 0

root = tk.Tk()

ru = tk.Button(root, text="Next", command=set_next)
ru.grid(column=0, row=0)

lab = tk.Label(root, text=values[current])
lab.grid(column=1, row=0)

ru2 = tk.Button(root, text="Previous", command=set_prev)
ru2.grid(column=2, row=0)

root.mainloop()

BTW: if Next has to show first element after last one 顺便说一句:如果Next必须显示最后一个元素之后的第一个元素

def set_next():
    global current

    current = (current + 1) % len(values)
    lab["text"] = values[current]

def set_prev():
    global current

    current = (current - 1) % len(values)
    lab["text"] = values[current]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM