How to get_lines from point to point in manim? - math

When I try to get_horizontal_line from one dot to another it goes from the y-axes. I want that the dashedline comes from the point [1;1] to point [3;1]. Because now it comes from [0;1] to[3;1]directly from the axis coordinate.
I don't know how to get lines not from the axis but from the point. Also here is my code:
from manim import *
class KvadratickaFunkcia(Scene):
def construct(self):
suradnicovaOs = Axes(
x_range=[-8,8,1],
y_range=[-8,8,1],
tips=False,
x_length=10,
y_length=10,
axis_config=
{
"stroke_color": GREY_A,
"include_numbers": True,
}
)
#vzorec x-2
posunParabolyVzorecMinus2a = MathTex("{y = (x-2)^2+0}", font_size=50).to_edge(UL).set_color(YELLOW)
posunParabolyVzorecMinus2a[0][5].set_color(RED)
posunParabolyVzorecMinus2a[0][9].set_color(RED)
#vzorec parabola y: (y-2)**2+0
parabolaMinus2a = suradnicovaOs.plot(lambda y: (y-2)**2+0 )
#body 1,2,3
bodMinus2a= Dot(suradnicovaOs.coords_to_point(1, 1), color=YELLOW)
bodkociarkaMinus2a = suradnicovaOs.get_horizontal_line(suradnicovaOs.c2p(3,1))
bodMinus2a2 = Dot(suradnicovaOs.coords_to_point(2, 0), color=YELLOW)
bodkociarkaMinus2a2 = suradnicovaOs.get_vertical_line(suradnicovaOs.c2p(1,1))
bodMinus2a3 = Dot(suradnicovaOs.coords_to_point(3, 1), color=YELLOW)
bodkociarkaMinus2a3 = suradnicovaOs.get_vertical_line(suradnicovaOs.c2p(3,1))
VsetkyBodyMinus123AA = VGroup(bodMinus2a,bodMinus2a2,bodMinus2a3,bodkociarkaMinus2a,bodkociarkaMinus2a2,bodkociarkaMinus2a3)
self.play(Write(suradnicovaOs), run_time=3)
self.play(Create(posunParabolyVzorecMinus2a))
self.play(Create(VsetkyBodyMinus123AA))
self.wait()
self.play(FadeIn(parabolaMinus2a))
image of my problem:

Welcome to the SO! You can use the .get_center() functions of the two points and connect them via DashedLine with stroke_width of 2. You should ignore bodkociarkaMinus2a and use the following line:
my_line: DashedLine = DashedLine(
bodMinus2a.get_center(), bodMinus2a3.get_center(),stroke_width = 2
)
Here is the full code:
from manim import *
class KvadratickaFunkcia(Scene):
def construct(self):
suradnicovaOs = Axes(
x_range=[-8,8,1],
y_range=[-8,8,1],
tips=False,
x_length=10,
y_length=10,
axis_config=
{
"stroke_color": GREY_A,
"include_numbers": True,
}
)
#vzorec x-2
posunParabolyVzorecMinus2a = MathTex("{y = (x-2)^2+0}", font_size=50).to_edge(UL).set_color(YELLOW)
posunParabolyVzorecMinus2a[0][5].set_color(RED)
posunParabolyVzorecMinus2a[0][9].set_color(RED)
#vzorec parabola y: (y-2)**2+0
parabolaMinus2a = suradnicovaOs.plot(lambda y: (y-2)**2+0 )
#body 1,2,3
bodMinus2a= Dot(suradnicovaOs.coords_to_point(1, 1), color=YELLOW)
#bodkociarkaMinus2a = suradnicovaOs.get_horizontal_line(suradnicovaOs.c2p(3,1))
bodMinus2a2 = Dot(suradnicovaOs.coords_to_point(2, 0), color=YELLOW)
bodkociarkaMinus2a2 = suradnicovaOs.get_vertical_line(suradnicovaOs.c2p(1,1))
bodMinus2a3 = Dot(suradnicovaOs.coords_to_point(3, 1), color=YELLOW)
bodkociarkaMinus2a3 = suradnicovaOs.get_vertical_line(suradnicovaOs.c2p(3,1))
my_line: DashedLine = DashedLine(
bodMinus2a.get_center(), bodMinus2a3.get_center(),stroke_width = 2
)
VsetkyBodyMinus123AA = VGroup(bodMinus2a,bodMinus2a2,bodMinus2a3, my_line, bodkociarkaMinus2a2, bodkociarkaMinus2a3)
self.play(Write(suradnicovaOs), run_time=3)
self.play(Create(posunParabolyVzorecMinus2a))
self.play(Create(VsetkyBodyMinus123AA))
self.wait()
self.play(FadeIn(parabolaMinus2a))

Related

Why do I get error "missing 1 required positional argument"?

Why I continue getting the error :
missing 1 required positional argument: 'category_id'
when the argument is already passed within query function in Backend class? I also don't understand the error of unfilled self or missing positional argument self:
missing 1 required positional argument: 'self'
I tried passing self to display_account_types() in Frontend class but it doesn't reflect. Do I need to pass self within the inner nested functions within a class?
import tkinter
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import sqlite3
root =Tk()
root.title('Simple Application')
root.config(bg='SlateGrey')
root.geometry("")
# BackEnd
class Backend():
def __init__(self):
self.conn = sqlite3.connect('accounting.db')
self.cur = self.conn.cursor()
self.conn.execute("""CREATE TABLE IF NOT EXISTS account_type(
id INTEGER PRIMARY KEY,
category_type INTEGER NOT NULL,
category_id TEXT NOT NULL
)"""),
self.conn.commit()
self.conn.close()
def insert_account_type(self, category_type, category_id):
self.conn = sqlite3.connect('accounting.db')
self.cur = self.conn.cursor()
self.cur.execute("""INSERT INTO account_type(category_id, category_type) VALUES(?,?);""",
(self,category_type, category_id,))
self.conn.commit()
self.conn.close()
def view_account_type(self):
self.conn = sqlite3.connect('accounting.db')
self.cur = self.conn.cursor()
self.cur.execute("SELECT * FROM account_type")
self.rows = self.cur.fetchall()
self.conn.close()
return self.rows
# calling the class
tb = Backend()
# Front End
class Frontend():
def __init__(self, master):
# Frames
self.top_frame = LabelFrame(master,bg ='SlateGrey', relief=SUNKEN)
self.top_frame.pack()
self.bottom_frame = LabelFrame(master, bg = 'SlateGrey', relief=SUNKEN)
self.bottom_frame.pack()
self.right_frame = LabelFrame(self.top_frame, bg = 'SlateGrey', relief = FLAT,
text = 'Details Entry',fg = 'maroon')
self.right_frame.pack(side = RIGHT, anchor = NE)
self.side_frame = LabelFrame(self.top_frame,bg ='SlateGrey',relief=SUNKEN,text = 'Menu Buttons',fg = 'maroon')
self.side_frame.pack(side = LEFT,anchor = NW)
self.bot_frame = LabelFrame(self.bottom_frame, bg='Grey',relief = SUNKEN,text = 'Field View',fg = 'maroon')
self.bot_frame.pack(side = BOTTOM,anchor = SW)
# Side Buttons
self.btn1 = Button(self.side_frame,
text='Main Account Types',
bg='SteelBlue4',
font=('cambria', 11),
anchor=W,
fg='white',
width=18,height=2,
command=lambda :[self.main_account()])
self.btn1.grid(row=0, column=0, pady=0, sticky=W)
def main_account(self):
# variables
self.category_type = StringVar()
self.category_id = StringVar()
# functions
def add_main_accounts():
if self.category_type.get() == "" or self.category_id.get() == "":
tkinter.messagebox.showinfo('All fields are required')
else:
Backend.insert_account_type(
self.category_type.get(),
self.category_id.get(),) # category type unfilled
tkinter.messagebox.showinfo('Entry successful')
def display_account_types(self):
self.trv.delete(*self.trv.get_children())
for self.rows in Backend.view_account_type(self):
self.trv.insert("", END, values=self.rows)
def get_account_type(e):
self.selected_row = self.trv.focus()
self.data = self.trv.item(self.selected_row)
global row
row = self.data["values"]
"""Grab items and send them to entry fields"""
self.category_id.set(row[1])
self.category_type.set(row[2])
"""=================TreeView==============="""
# Scrollbars
ttk.Style().configure("Treeview", background = "SlateGrey", foreground = "white", fieldbackground = "grey")
scroll_x = Scrollbar(self.bot_frame, orient = HORIZONTAL)
scroll_x.pack(side = BOTTOM, fill = X)
scroll_y = Scrollbar(self.bot_frame, orient = VERTICAL)
scroll_y.pack(side = RIGHT, fill = Y)
# Treeview columns & setting scrollbars
self.trv = ttk.Treeview(self.bot_frame, height=3, columns=
('id', 'category_id', 'category_type'), xscrollcommand = scroll_x.set, yscrollcommand = scroll_y.set)
# Treeview style configuration
ttk.Style().configure("Treeview", background = "SlateGrey", foreground = "white", fieldbackground = "grey")
# Configure vertical and Horizontal scroll
scroll_x.config(command = self.trv.xview)
scroll_y.config(command = self.trv.yview)
# Treeview Headings/columns
self.trv.heading('id', text = "No.")
self.trv.heading('category_id', text = 'Category ID')
self.trv.heading('category_type', text = 'Category Type')
self.trv['show'] = 'headings'
# Treeview columns width
self.trv.column('id', width = 23)
self.trv.column('category_id', width = 70)
self.trv.column('category_type', width = 100)
self.trv.pack(fill = BOTH, expand = YES)
# Binding Treeview with data
self.trv.bind('<ButtonRelease-1>',get_account_type)
# Account Types Labels
self.lbl1 = Label(self.right_frame,text = 'Category ID',anchor = W,
width=10,font = ('cambria',11,),bg = 'SlateGrey')
self.lbl1.grid(row = 0,column = 0,pady = 5)
self.lbl2 = Label(self.right_frame, text = 'Category Type', anchor = W,
width = 10,font = ('cambria',11,),bg = 'SlateGrey')
self.lbl2.grid(row = 1, column = 0,pady = 5,padx=5)
self.blank_label = Label(self.right_frame, bg='SlateGrey')
self.blank_label.grid(row=2, columnspan=2, pady=10)
# Account Type Entries
self.entry1 = Entry(self.right_frame,textvariable = self.category_id,
font = ('cambria',11,),bg = 'Grey',width=14)
self.entry1.grid(row = 0,column=1,sticky = W,padx = 5)
self.entry2 = Entry(self.right_frame, textvariable = self.category_type,
font = ('cambria', 11,), bg = 'Grey',width = 14)
self.entry2.grid(row = 1, column = 1, sticky = W,pady = 5,padx = 5)
# Buttons
self.btn_1 = Button(self.right_frame,text = 'Add',font = ('cambria',12,'bold'),bg = 'SlateGrey',
activebackground='green', fg = 'white',width=12,height = 2,relief=RIDGE,
command = lambda :[add_main_accounts()])
self.btn_1.grid(row = 3,column = 0,pady = 15)
self.btn_2 = Button(self.right_frame, text = 'View', font = ('cambria', 12, 'bold'),
bg = 'SlateGrey',command=lambda :[display_account_types()],
activebackground='green', fg ='white', width=12, height = 2, relief = RIDGE)
self.btn_2.grid(row = 3, column = 1)
# calling the class
app = Frontend(root)
root.mainloop()
I got and answer to this question,
I just passed in the 'self' argument to the inner nested functions of the class as below and it worked.
# functions
def add_main_accounts(self):
if self.category_id.get() == "" or self.category_type.get() == "":
tkinter.messagebox.showinfo('All fields are required')
else:
Backend.insert_account_type(self,
self.category_id.get(),
self.category_type.get()) # category type unfilled
tkinter.messagebox.showinfo('Entry successful')
def display_account_types(self):
self.trv.delete(*self.trv.get_children())
for rows in Backend.view_account_type(self):
self.trv.insert("", END, values = rows)
return
def get_account_type(e):
self.selected_row = self.trv.focus()
self.data = self.trv.item(self.selected_row)
global row
self.row = self.data["values"]
"""Grab items and send them to entry fields"""
self.category_id.set(row[1])
self.category_type.set(row[2])
I think you should remove the self in display_account_types function like you did to the previous one.

highcharter custom animation

I'm trying to add a custom animation using highcharter R package like in this example where I use a polar chart.
I'm able to do this using JS, but I can't translate the animation function (from ease repository) to highcharter.
Here is my R code:
# I've tried to created a function using `JS`:
easeOutBounce <- JS("function (pos) {
if ((pos) < (1 / 2.75)) {
return (7.5625 * pos * pos);
}
if (pos < (2 / 2.75)) {
return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
}
if (pos < (2.5 / 2.75)) {
return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
}
return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
}")
library(tidyverse)
library(highcharter)
highchart() %>%
hc_chart(polar = T, type = "bar",
events = list(
render = JS("function() {
var chart = this,
middleElement = chart.middleElement;
if (middleElement) {
middleElement.destroy();
}
chart.middleElement = chart.renderer.circle(chart.plotSizeX / 2 + chart.plotLeft, chart.plotHeight / 2 + chart.plotTop, 20).attr({
zIndex: 3,
fill: '#ffffff'
}).add();
}")
)
) %>%
hc_title(text = "Athlete 1 vs Athlete 2") %>%
hc_xAxis(categories = c("Total Score", "Avg. Score", "Sum Score",
"Best Score"),
tickmarkPlacement = "on",
plotLines = list(
list(label = list(
rotation = 90))
)
) %>%
hc_yAxis(offset = 30) %>%
hc_series(
list(
pointPadding = 0,
groupPadding = 0,
name = "Athlete 1",
animatio = list(
duration = 1000,
easing = easeOutBounce
),
data = c(43000, 19000, 60000, 35000)
),
list(
pointPadding = 0,
groupPadding = 0,
name = "Athlete 2",
data = c(50000, 39000, 42000, 31000)
)
) %>%
hc_colors(c("firebrick", "steelblue")) %>%
hc_tooltip(
borderWidth = 0,
backgroundColor = 'none',
shadow = FALSE,
style = list(
fontSize = '16px'
),
headerFormat = '',
pointFormatter = JS("function() {
return this.y / 1000 + 'k'
}"),
positioner = JS("function(labelWidth, labelHeight) {
return {
x: (this.chart.plotSizeX - labelWidth) / 2 + this.chart.plotLeft,
y: (this.chart.plotSizeY - labelHeight) / 2 + this.chart.plotTop
};
}")
)
Thank you!
Animation doesn't work because you have a little typo in attached code. Please take a look on it:
animatio = list(
duration = 1000,
easing = easeOutBounce
),
Should be animation, not animatio. Please correct it, then animation should appear.

Error when implementing a custom layer in keras for R

I am trying to implement a custom layer for the package keras in R (github).
The layer I am implementing is based on this AttentionWithContext layer available here: gist
Here is my code:
AttentionWithContext <- R6::R6Class("AttentionWithContext",
inherit = KerasLayer,
public = list(
W_regularizer = NULL,
b_regularizer = NULL,
u_regularizer = NULL,
W_constraint=NULL,
b_constraint=NULL,
u_constraint=NULL,
bias=NULL,
b=NULL,
W=NULL,
u=NULL,
supports_masking=NULL,
init=NULL,
name = NULL,
initialize = function(name = 'attention',
W_regularizer = NULL,
b_regularizer = NULL,
u_regularizer = NULL,
W_constraint=NULL,
b_constraint=NULL,
u_constraint=NULL,
bias=TRUE ) {
self$supports_masking = TRUE
self$init = keras::initializer_glorot_uniform()
self$W_regularizer = W_regularizer
self$b_regularizer = b_regularizer
self$u_regularizer = u_regularizer
self$W_constraint = W_constraint
self$b_constraint = b_constraint
self$u_constraint = u_constraint
self$bias = bias
self$name = name
},
build = function(input_shape) {
assertthat::assert_that(length(input_shape) == 3)
self$W = self$add_weight(shape = reticulate::tuple(input_shape[[3]],input_shape[[3]], NULL),
initializer = self$init,
name=stringr::str_interp('${self$name}_W'),
regularizer = self$W_regularizer,
constraint = self$W_constraint)
if (self$bias) {
self$b = self$add_weight(shape = reticulate::tuple(input_shape[[3]]),
initializer='zero',
name = stringr::str_interp('${self$name}_b'),
regularizer = self$b_regularizer,
constraint = self$b_constraint)
}
self$u = self$add_weight(shape = reticulate::tuple(input_shape[[3]]),
initializer=self$init,
name = stringr::str_interp('${self$name}_u'),
regularizer = self$u_regularizer,
constraint = self$u_constraint)
},
compute_mask = function(input, input_mask=NULL) {
return(NULL)
},
call = function(x, mask = NULL) {
uit = keras::k_squeeze(keras::k_dot(x, keras::k_expand_dims(self$W)), axis=-1)
if (self$bias) {
uit = uit + self$b
}
uit = keras::k_tanh(uit)
ait = keras::k_dot(uit, self$u)
a = keras::k_exp(ait)
if (!is.null(mask)) {
a = a * keras::k_cast(mask, keras::k_floatx())
}
a = a/keras::k_cast(keras::k_sum(a, axis = 1, keepdims = TRUE) + keras::k_epsilon(), keras::k_floatx())
weighted_input = x * keras::k_expand_dims(a)
keras::k_sum(weighted_input, axis=1)
},
compute_output_shape = function(input_shape) {
list(input_shape[[1]], input_shape[[3]])
}
)
)
# define layer wrapper function
layer_attention_with_context <- function(object, W_regularizer = NULL,
b_regularizer = NULL,
u_regularizer = NULL,
W_constraint=NULL,
b_constraint=NULL,
u_constraint=NULL,
bias=TRUE,
name = 'attention_with_context') {
create_layer(AttentionWithContext, object, list(W_regularizer = W_regularizer,
b_regularizer = b_regularizer,
u_regularizer = u_regularizer,
W_constraint= W_constraint,
b_constraint=b_constraint,
u_constraint=u_constraint,
bias=bias,
name = name
))
}
# Example
model <- keras_model_sequential()
model %>%
layer_embedding(input_dim = 20000,
output_dim = 128,
input_length = 30) %>%
layer_lstm(64, return_sequences = TRUE) %>%
layer_attention_with_context() %>%
time_distributed(layer_dense(units=10))
When I run this, I get a cryptic error message:
Error in py_call_impl(callable, dots$args, dots$keywords) :
RuntimeError: Evaluation error: TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'.
I tried to explore this error and I think it might come from this line :
reticulate::tuple(input_shape[[3]],input_shape[[3]], NULL)
In the original code, in python, we can see this:
(input_shape[-1], input_shape[-1],)
I could not find a way to create this structure in R.
Any ideas ?

Maximum value of QSlider?

What is the maximum value of QSlider, in the datasheet, it is just mentioned as int.
I tried with "1000000". but the Slider starts bugging.
QSlider.setMaximum(1000000);
Image with the bug, the blue color and the cursor don't move well at same speed, if the number is at max : 999999999, the cursor don't move at all.
when I put : max at : 650000 that works very well. That is perhaps an OS problem, I am using IOS..
By the way, here is an update of code, works fine with 100000 x 2 possible values:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
MAXVAL = 650000
class RangeSliderClass(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.minTime = 0
self.maxTime = 0
self.minRangeTime = 0
self.maxRangeTime = 0
self.middleTime = self.getMiddleTime()
self.halfTimeInterval = self.middleTime - self.minTime
self.sliderMin = MAXVAL
self.sliderMax = MAXVAL
self.setupUi(self)
def setupUi(self, RangeSlider):
RangeSlider.setObjectName("RangeSlider")
RangeSlider.resize(631, 65)
RangeSlider.setMaximumSize(QtCore.QSize(16777215, 65))
self.RangeBarVLayout = QtWidgets.QVBoxLayout(RangeSlider)
self.RangeBarVLayout.setContentsMargins(5, 0, 5, 0)
self.RangeBarVLayout.setSpacing(0)
self.RangeBarVLayout.setObjectName("RangeBarVLayout")
self.datesFrame = QtWidgets.QFrame(RangeSlider)
self.datesFrame.setMaximumSize(QtCore.QSize(16777215, 28))
self.datesFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.datesFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.datesFrame.setObjectName("datesFrame")
self.datesHLayout = QtWidgets.QHBoxLayout(self.datesFrame)
self.datesHLayout.setContentsMargins(5, 2, 5, 2)
self.datesHLayout.setObjectName("datesHLayout")
## startTime Calendar Widget
self.startTime = QtWidgets.QDateTimeEdit(self.datesFrame)
self.startTime.setMinimumSize(QtCore.QSize(183, 0))
self.startTime.setMaximumSize(QtCore.QSize(185, 24))
self.startTime.setDate(QtCore.QDate.currentDate().addDays(-1))
self.startTime.setMaximumDateTime(QtCore.QDateTime(QtCore.QDate(2999, 12, 31), QtCore.QTime(23, 59, 59)))
self.startTime.setMaximumDate(QtCore.QDate(2999, 12, 31))
self.startTime.setMinimumDate(QtCore.QDate(2000, 1, 1))
self.startTime.setCalendarPopup(True)
self.startTime.setObjectName("startTime")
self.startTime.dateChanged.connect(self.startDateChangeHandler)
self.datesHLayout.addWidget(self.startTime)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.datesHLayout.addItem(spacerItem)
## entTime Calendar Widget
self.endTime = QtWidgets.QDateTimeEdit(self.datesFrame)
self.endTime.setMinimumSize(QtCore.QSize(183, 0))
self.endTime.setMaximumSize(QtCore.QSize(185, 24))
self.endTime.setDate(QtCore.QDate.currentDate())
self.endTime.setMaximumDate(QtCore.QDate(2999, 12, 31))
self.endTime.setMinimumDate(QtCore.QDate(2000, 1, 1))
self.endTime.setCalendarPopup(True)
self.endTime.setObjectName("endTime")
self.endTime.dateChanged.connect(self.endDateChangeHandler)
self.datesHLayout.addWidget(self.endTime)
## Init Time
self.minTime = self.startTime.dateTime().toTime_t()
self.maxTime = self.endTime.dateTime().toTime_t()
self.minRangeTime = self.minTime
self.maxRangeTime = self.maxTime
self.middleTime = self.getMiddleTime()
self.halfTimeInterval = self.middleTime - self.minTime
self.RangeBarVLayout.addWidget(self.datesFrame)
self.slidersFrame = QtWidgets.QFrame(RangeSlider)
self.slidersFrame.setMaximumSize(QtCore.QSize(16777215, 25))
self.slidersFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.slidersFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.slidersFrame.setObjectName("slidersFrame")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.slidersFrame)
self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.horizontalLayout.setContentsMargins(5, 2, 5, 2)
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setObjectName("horizontalLayout")
## Start Slider Widget
self.startSlider = QtWidgets.QSlider(self.slidersFrame)
self.startSlider.setMaximum(self.sliderMin)
self.startSlider.setMinimumSize(QtCore.QSize(100, 5))
self.startSlider.setMaximumSize(QtCore.QSize(16777215, 10))
font = QtGui.QFont()
font.setKerning(True)
self.startSlider.setFont(font)
self.startSlider.setAcceptDrops(False)
self.startSlider.setAutoFillBackground(False)
self.startSlider.setOrientation(QtCore.Qt.Horizontal)
self.startSlider.setInvertedAppearance(True)
self.startSlider.setObjectName("startSlider")
self.startSlider.setValue(MAXVAL)
self.startSlider.sliderReleased.connect(self.startSliderHandler)
self.horizontalLayout.addWidget(self.startSlider)
## End Slider Widget
self.endSlider = QtWidgets.QSlider(self.slidersFrame)
self.endSlider.setMaximum(MAXVAL)
self.endSlider.setMinimumSize(QtCore.QSize(100, 5))
self.endSlider.setMaximumSize(QtCore.QSize(16777215, 10))
self.endSlider.setTracking(True)
self.endSlider.setOrientation(QtCore.Qt.Horizontal)
self.endSlider.setObjectName("endSlider")
self.endSlider.setValue(self.sliderMax)
self.endSlider.sliderReleased.connect(self.endSliderHandler)
self.horizontalLayout.addWidget(self.endSlider)
self.RangeBarVLayout.addWidget(self.slidersFrame)
self.retranslateUi(RangeSlider)
QtCore.QMetaObject.connectSlotsByName(RangeSlider)
self.show()
def getMiddleTime(self, maxTime = None, minTime = None):
if minTime == None :
minTime = self.minRangeTime
if maxTime == None :
maxTime = self.maxRangeTime
return (minTime + maxTime)/2
def getRangeTime(self):
return self.minRangeTime, self.maxRangeTime
def startSliderHandler(self):
self.sliderMin = self.startSlider.value()
self.minRangeTime = int(self.middleTime - self.halfTimeInterval * self.sliderMin / MAXVAL)
#print("\n\nNew Min Time Range : ", self.minRangeTime, " Min : ", self.minTime, "Minddle : ", self.middleTime)
def endSliderHandler(self):
self.sliderMax = self.endSlider.value()
self.maxRangeTime = int(self.middleTime + self.halfTimeInterval * self.sliderMax / MAXVAL)
print("\n\nNew Min Time Range : ", self.maxRangeTime, " Max : ", self.maxTime, "Minddle : ", self.middleTime)
def startDateChangeHandler(self):
self.minTime = self.startTime.dateTime().toTime_t()
#print("MinTime range : ", self.minTime)
def endDateChangeHandler(self):
self.maxTime = self.endTime.dateTime().toTime_t()
#print("MaxTime range : ", self.maxTime)
def retranslateUi(self, RangeSlider):
_translate = QtCore.QCoreApplication.translate
RangeSlider.setWindowTitle(_translate("RangeSlider", "Time interval"))
self.startTime.setDisplayFormat(_translate("RangeSlider", "dd/MM/yyyy HH:mm:ss .zz"))
self.endTime.setDisplayFormat(_translate("RangeSlider", "dd/MM/yyyy HH:mm:ss .zz"))
app = QtWidgets.QApplication(sys.argv)
awindow = RangeSliderClass()
sys.exit(app.exec_())
You can set QSlider maximum value with 9 digits.
QSlider.setMaximum(999999999);
The answer of #aghilpro is not incorrect on Qt Designer the limit is 999999999 (9 digits)
But QSlider inherits QAbstractSlider and on definition of properties we have:
...
Q_PROPERTY(int minimum READ minimum WRITE setMinimum)
Q_PROPERTY(int maximum READ maximum WRITE setMaximum)
...
Then the max int value is 2,147,483,647 (10 digits) then 9999999999 overflow that value;

Tkinter Module refresh window

My program is for a hangman game and I can't get the window to refresh once the button is clicked. At least i think that is the problem Here is my code for the window and the function linked to the button, let me know if you need more code:
def game(self, num):
self.game_window = tkinter.Tk()
self.game_window.title('Hangman')
self.game_window.geometry('200x150')
self.f1 = tkinter.Frame(self.game_window)
self.f2 = tkinter.Frame(self.game_window)
self.f3 = tkinter.Frame(self.game_window)
self.f4 = tkinter.Frame(self.game_window)
self.f5 = tkinter.Frame(self.game_window)
self.f6 = tkinter.Frame(self.game_window)
self.f7 = tkinter.Frame(self.game_window)
self.f8 = tkinter.Frame(self.game_window)
self.f9 = tkinter.Frame(self.game_window)
self.num = num
word_list = ['PYTHON','SOMETHING','COMPLETELY','DIFFERENT',
'LIST','STRING','SYNTAX','OBJECT','ERROR',
'EXCEPTION','OBJECT','CLASS','PERFORMANCE','VISUAL',
'JAVASCRIPT','JAVA','PROGRAMMING','TUPLE','ASSIGN',
'FUNCTION','OPERATOR','OPERANDS','PRECEDENCE',
'LOOPS','SENTENCE','TABLE','NUMBERS','DICTIONARY',
'GAME','SOFTWARE','NETWORK','SOCIAL','EDUCATION',
'MONITOR','COMPUTER']
shuffle = random.shuffle(word_list)
rand = random.choice(word_list)
self.word = rand.lower()
self.current = len(self.word)*'*'
self.letters = []
#self.start_lives = tkinter.Label(self.f1, text = 'You\'ve started the '
#'game with %s lives.\n'%(self.num))
#self.start_lives.pack(side = 'left')
self.lives_rem = tkinter.Label(self.f2,
text = 'Lives remaining: '+str(self.lives_left()))
self.lives_rem.pack(side = 'left')
self.guess_letter = tkinter.Label(self.f3, text = 'Guess a letter: ')
self.guess_entry = tkinter.Entry(self.f3, width = 10)
self.guess_letter.pack(side = 'left')
self.guess_entry.pack(side = 'left')
#self.f1.pack()
self.f2.pack()
self.f3.pack()
self.guess_button = tkinter.Button(self.f6,
text = 'Guess!',
command = self.update(self.guess_entry.get()))
self.guess_button.pack(side = 'left')
self.quit_game = tkinter.Button(self.f6,
text = 'Quit Game',
command = self.game_window.destroy)
self.quit_game.pack(side = 'left')
self.f6.pack()
def update(self, letter):
if letter in self.word and letter not in self.letters:
pos = self.word.index(letter)
self.current1 = list(self.current)
self.current1[pos] = letter.upper()
self.current2 = ''.join(self.current1)
self.letters.append(letter)
elif letter in self.letters:
self.already_guessed = tkinter.messagebox.showinfo('Error!',
'This letter has already '
'been guessed')
#letter is not in the word
elif letter not in self.word:
self.sorry = tkinter.Label(self.f5,
text = 'Sorry, guess again!')
self.sorry.pack(side = 'left')
self.letters.append(letter)
self.num -= 1
self.incorrect_word = tkinter.Label(self.f4,
text = 'Word: '+self.current)
self.incorrect_word.pack(side='left')
self.f5.pack()
self.f4.pack()
return self.current
These are two methods in a Hangman class.
The line that defines the guess button:
self.guess_button = tkinter.Button(self.f6, text = 'Guess!', command = self.update(self.guess_entry.get()))
requires modification. the command argument for the Button class should be a function, but this line is calling that function (which sends the output of the function as the value for the command argument). As you may see on the quit_game button definition, the self.game_window.destroy function is provided as the command, but is not called right now.
I suggest changing this line like this:
self.guess_button = tkinter.Button(self.f6, text = 'Guess!', command = self._on_guess_button_click)
and then add a new method to your class like this:
def _on_guess_button_click (self):
self.update(self.guess_entry.get())

Resources