I'm currently creating a library for a blackjack simulator in Python. Connecting to the simulator is a Tkinter GUI which controls the input. I want the input to range from 1-50,000,000; however, I want users to be able to easily select smaller number ranges such as 15,000-75,000.
I figure the best way to do this would be by having the range of values in the slider update using f(x)=x^2 instead of it's normal linear behavior.
I believe I could create a new widget which displays the value of the f(x)=x^2 function where the input is slider.get() of the slider widget. But I was hoping someone knows of a more elegant solution that could display and use this f(x)=x^2 value using the slider widget itself.
Here's basic widget code ripped off of a tutorial's point example found here: https://www.tutorialspoint.com/python/tk_scale.htm
def sel():
selection = "Value = " str(var.get())
label.config(text = selection)
root = Tk()
var = DoubleVar()
scale = Scale( root, variable = var )
scale.pack(anchor=CENTER)
button = Button(root, text="Get Scale Value", command=sel)
button.pack(anchor=CENTER)
label = Label(root)
label.pack()
root.mainloop()```
CodePudding user response:
You can create a version of the Scale widget that will return the value of the slider but with a specific mathematically function applied. In the example below I return x^2.
import tkinter as tk
def sel():
selection = "Value = " str(scale2.value)
label.config(text = selection)
class LogScale(tk.Scale):
def __init__(self,parent,**kwargs):
tk.Scale.__init__(self,parent,**kwargs)
self.var = tk.DoubleVar()
#self.config[showvalue] = 0
self['showvalue'] = 0
self['label'] = 0
self['command'] = self.update
self['variable'] = self.var
def update(self,event):
self.config(label=self.value)
@property
def value(self):
return str(int(self.var.get()) ** 2)
root = tk.Tk()
scale2 = LogScale(root)
scale2.pack()
button = tk.Button(root, text="Get Scale Value", command=sel)
button.pack(anchor=tk.CENTER)
label = tk.Label(root)
label.pack()
root.mainloop()
I've hidden the normal label that moves alongside the slider and have used the other label to display the "modified" value.