0

I am trying to make a slider in python with tkinter, and have a loop continuously update the data from the slider. In the end product I want a row of leds light up verbatim to the slider. The problem is that the while loop stops the rest of the code from working and the window with the slider won't open. Here is my code:

import RPi.GPIO as GPIO
from tkinter import * 
GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.OUT) 
GPIO.setwarnings(False)

def value():
       led.get() 

master = Tk()
master.geometry('100x100')
led = Scale(master, from_=5, to=1) 
led.pack()

while True: 
        print(value()) 

mainloop() 
  • tkinter has `root.after(millisecond, function)` which you can use to change something and run again `root.after(millisecond, function)` to chage again little later, etc. – furas Apr 15 '20 at 21:22
  • 1
    Read [tkinter-how-to-use-after-method](https://stackoverflow.com/questions/25753632) – stovfl Apr 15 '20 at 21:27
  • maybe you should use `Scale(..., command=on_change)` to run function `on_change` when `Scale` changes value - and you will no need loop. See my answer. – furas Apr 15 '20 at 21:38

1 Answers1

0

tkinter has root.after(millisecond, function) to run function with some delay and you can use it to repeate some function - so it will work similar to loop but it will not block mainloop()

import tkinter as tk # PEP8: `import *` is not preferred

# --- function ---

def value():
    print(led.get())

    # run again after 1000ms 
    master.after(1000, value)

# --- main --

master = tk.Tk()

led = tk.Scale(master, from_=5, to=1) 
led.pack()

# run first time at once
#value()

# or run fist time after 1000ms
master.after(1000, value)

master.mainloop() 

BTW: In after() you have to use function's name without () and without arguments. If you need to run with arguments then master.after(1000, value, arg1, arg2, ...)


PEP 8 -- Style Guide for Python Code


BTW: You can assign function to Scale and it will run it when `Scale changes value - and you will no need loop to check it.

import tkinter as tk # PEP8: `import *` is not preferred

# --- function ---

def on_change(new_value):
    print(led.get())
    print(new_value)

# --- main --

master = tk.Tk()

led = tk.Scale(master, from_=5, to=1, command=on_change) 
led.pack()

master.mainloop() 

Documentation (effbot.org): Scale

furas
  • 134,197
  • 12
  • 106
  • 148