How do I store an integer input from the user into a variable in Tkinter? - variables

For my Python class were using turtle graphics.
We have too draw a target that appears at a random location on the screen. Got that.
Then a pop up window appears asking for what you think the coordinates of the target are. First the pop up box asks you to enter the x coordinate then it asks you to enter the y coordinate.
I'm having trouble saving the users inputed integers from my Tkinter window into variables I can use later in the program.
from Tkinter import *
window = Tk()
window.title("Player Input")
window.geometry('+350+130')
thexinput = IntVar()
L1 = Label(window, text="Enter the x coordinate for Mike")
L1.pack( side = LEFT)
E1= Entry(window, textvariable= thexinput, bd =5)
E1.pack(side = RIGHT)
def userinput():
global inp
a = raw_input(thexinput.get())
inp = a
b = Button(window, text = 'Submit', command = userinput)
b.pack(side = BOTTOM)
window.mainloop()

You don't need to use raw_input, you just need to call the get method of the entry widget.
a = thexinput.get()

Related

Resize border of qgraphicstextitem

I am adding a QGraphicTextItem to a scene using pyqt6.
I cannot resize the widget border when text is resized.
I have looked at a few way of resizing, but none work.
The text does change to a bigger font via the context menu.
The entire class is shown below.
class FreeTextGraphicsItem(QtWidgets.QGraphicsTextItem):
def __init__(self, x, y, text_):
super(FreeTextGraphicsItem, self).__init__(None)
self.x = x
self.y = y
self.text = text_
self.setFlags(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsMovable |
QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsFocusable |
QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsSelectable)
self.font = QtGui.QFont(self.settings['font'], 9, QtGui.QFont.Weight.Normal)
self.setFont(self.font)
self.setPlainText(self.text)
self.setPos(self.x, self.y)
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu()
menu.addAction(_("Large font"))
action = menu.exec(QtGui.QCursor.pos())
if action is None:
return
if action.text() == "Large font":
self.font = QtGui.QFont(self.settings['font'], 12, QtGui.QFont.Weight.Normal)
frame = self.document().documentLayout().frameBoundingRect(self.document().rootFrame())
self.boundingRect().setRect(0, 0, frame.width(), frame.height())
def paint(self, painter, option, widget):
color = QtCore.Qt.GlobalColor.white
painter.setBrush(QtGui.QBrush(color, style=QtCore.Qt.BrushStyle.SolidPattern))
painter.drawRect(self.boundingRect())
painter.setFont(self.font)
fm = painter.fontMetrics()
painter.setPen(QtGui.QColor(QtCore.Qt.GlobalColor.black))
lines = self.text.split('\\n')
for row in range(0, len(lines)):
painter.drawText(5, fm.height() * (row + 1), lines[row])
You're not using the features of QGraphicsTextItem.
In fact, you're completely ignoring and overriding most of its aspects:
x and y are existing and dynamic properties of all QGraphicsItems and should never be overwritten;
the same for font of QGraphicsTextItem;
calling setRect() on the bounding rectangle is useless, as boundingRect() is a *property getter" and is returned internally by the item based on its contents (in this case, the text set with setPlainText());
the text drawing is completely overridden, and not reliable nor consistent with the text set for the item, considering that you're painting the text with split lines, while the original text has escaped new lines;
If your main purpose is to draw a border around the item, then you should only do that, and then rely on the existing capabilities of the item.
class FreeTextGraphicsItem(QtWidgets.QGraphicsTextItem):
def __init__(self, x, y, text_):
super().__init__(text_.replace('\\n', '\n'))
self.setPos(x, y)
self.setFlags(
QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsMovable
| QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsFocusable
| QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsSelectable
)
font = QtGui.QFont(self.settings['font'], 9, QtGui.QFont.Weight.Normal)
self.setFont(font)
self.setDefaulTextColor(QtGui.QColor(QtCore.Qt.GlobalColor.white))
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu()
largeFontAction = menu.addAction(_("Large font"))
action = menu.exec(event.screenPos())
if action == largeFontAction:
font = QtGui.QFont(
self.settings['font'], 12, QtGui.QFont.Weight.Normal)
self.setFont(font)
def paint(self, painter, option, widget=None):
painter.save()
painter.setBrush(QtCore.Qt.GlobalColor.white)
painter.drawRect(self.boundingRect())
painter.restore()
super().paint(painter, option, widget)
Note: comparing actions with their text is pointless, other than conceptually wrong; not only you can have a more reliable object-based comparison using the action (as shown above), but that comparison can also become invalid: a menu could contain items that have the same names, and you're also probably using the _ for translations, so the text might not match at all.

How to use hover events in mpl_connect in matplotlib

I'm working on line plotting a metric for a course module as well as each of its questions within a Jupyter Notebook using %matplotlib notebook. That part is no problem. A module has typically 20-35 questions, so it results in a lot of lines on a chart. Therefore, I am plotting the metric for each question in a low alpha and I want to change the alpha and display the question name when I hover over the line, then reverse those when no longer hovering over the line.
The thing is, I've tried every test version of interactivity from the matplotlib documentation on event handling, as well as those in this question. It seems like the mpl_connect event is never firing, whether I use click or hover.
Here's a test version with a reduced dataset using the solution to the question linked above. Am I missing something necessary to get events to fire?
def update_annot(ind):
x,y = line.get_data()
annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])
text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))),
" ".join([names[n] for n in ind["ind"]]))
annot.set_text(text)
annot.get_bbox_patch().set_alpha(0.4)
def hover(event):
vis = annot.get_visible()
if event.inaxes == ax:
cont, ind = line.contains(event)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
module = 'bd2bc472-ee0d-466f-8557-788cc6de3018'
module_metrics[module] = {
'q_count': 31,
'sequence_pks': [0.5274546300604932,0.5262044653349001,0.5360993905297703,0.5292329279700655,0.5268691588785047,0.5319099014547161,0.5305164319248826,0.5268235294117647,0.573648805381582,0.5647933116581514,0.5669839795681448,0.5646591970121382,0.5663157894736842,0.5646976090014064,0.5659005628517824,0.5693634879925391,0.5728268468888371,0.5668834184858337,0.5687237026647967,0.5795640965549567,0.5877684407096172,0.585690904839841,0.5766899766899767,0.5971341320178529,0.6059972105997211,0.6055516678329834,0.6209865053513262,0.6203121360354065,0.6153666510976179,0.6236909471724459,0.6387654898293196],
'q_pks': {
'0da04f02-4aad-4ac8-91a5-214862b5c0d0': [0.6686046511627907,0.6282051282051282,0.76,0.6746987951807228,0.7092198581560284,0.71875,0.6585365853658537,0.7070063694267515,0.7171052631578947,0.7346938775510204,0.7737226277372263,0.7380952380952381,0.6774193548387096,0.7142857142857143,0.7,0.6962962962962963,0.723404255319149,0.6737588652482269,0.7232704402515723,0.7142857142857143,0.7164179104477612,0.7317073170731707,0.6333333333333333,0.75,0.7217391304347827,0.7017543859649122,0.7333333333333333,0.7641509433962265,0.6869565217391305,0.75,0.794392523364486],
'10bd29aa-3a26-49e6-bc2c-50fd503d7ab5': [0.64375,0.6014492753623188,0.5968992248062015,0.5059523809523809,0.5637583892617449,0.5389221556886228,0.5576923076923077,0.51875,0.4931506849315068,0.5579710144927537,0.577922077922078,0.5467625899280576,0.5362318840579711,0.6095890410958904,0.5793103448275863,0.5159235668789809,0.6196319018404908,0.6143790849673203,0.5035971223021583,0.5897435897435898,0.5857142857142857,0.5851851851851851,0.6164383561643836,0.6054421768707483,0.5714285714285714,0.627906976744186,0.5826771653543307,0.6504065040650406,0.5864661654135338,0.6333333333333333,0.6851851851851852]
}}
suptitle_size = 24
title_size = 18
tick_size = 12
axis_label_size = 15
legend_size = 14
fig, ax = plt.subplots(figsize=(15,8))
fig.suptitle('PK by Sequence Order', fontsize=suptitle_size)
module_name = 'Test'
q_count = module_metrics[module]['q_count']
y_ticks = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
x_ticks = np.array([x for x in range(0,q_count)])
x_labels = x_ticks + 1
# Plot it
ax.set_title(module_name, fontsize=title_size)
ax.set_xticks(x_ticks)
ax.set_yticks(y_ticks)
ax.set_xticklabels(x_labels, fontsize=tick_size)
ax.set_yticklabels(y_ticks, fontsize=tick_size)
ax.set_xlabel('Sequence', fontsize=axis_label_size)
ax.set_xlim(-0.5,q_count-0.5)
ax.set_ylim(0,1)
ax.grid(which='major',axis='y')
# Output module PK by sequence
ax.plot(module_metrics[module]['sequence_pks'])
# Output PK by sequence for each question
for qid in module_metrics[module]['q_pks']:
ax.plot(module_metrics[module]['q_pks'][qid], alpha=0.15, label=qid)
annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
mpl_id = fig.canvas.mpl_connect('motion_notify_event', hover)
Since there are dozens of modules, I created an ipywidgets dropdown to select the module, which then runs a function to output the chart. Nonetheless, whether running it hardcoded as here or from within the function, mpl_connect never seems to fire.
Here's what this one looks like when run

Blender: How can I exclude an object from another?

Blender: How can i exclude an object from another so that I'm left with an object with holes in it?
I'm currently trying to create a 3.951x2.610x0.05 box with holes across it. The holes are 0.1x0.1x0.5. I select them all but I don't know how to exclude them from the box
The hole height should be the same as box height, right?
Say it's both 0.5 in below example script:
import bpy
epsilon = 10e-5
bpy.ops.mesh.primitive_cube_add()
bpy.ops.transform.resize(value=(3.951,2.610,0.5))
obj_A = bpy.context.object
bpy.ops.mesh.primitive_cube_add()
bpy.ops.transform.resize(value=(0.1,0.1,0.5+epsilon))
obj_B = bpy.context.object
bpy.ops.object.select_all(action='DESELECT')
bpy.context.scene.objects.active = obj_A
obj_modifier = obj_A.modifiers.new('myBoolModifier', 'BOOLEAN')
obj_modifier.object = obj_B
obj_modifier.operation = 'DIFFERENCE'
bpy.ops.object.modifier_apply(apply_as='DATA', modifier="myBoolModifier")
bpy.context.scene.objects.unlink(obj_B)
The output:

Access windows for notebook in Tkinter

I have been trying to create an open windows which asks you for username and password before opening a notebook in Tkinter, I have both, but I don't know how to put them together. In other words, what I want is to open a notebook once the username and password requested are correct.
Thank you very much in advance!
What I have done so far is as follows:
import Tkinter
from Tkinter import *
import ttk
from ttk import * #Combobox Definition
import tkMessageBox #for Welcome Message
import Tkinter as tk # For Main Frame Definition
from Tkinter import Tk, Text, BOTH, W, N, E, S
from ttk import Frame, Button, Label, Style
root = Tk()
root.title("Model A")
root.minsize(400, 220)
root.maxsize(410, 240)
# start of Notebook (multiple tabs)
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand='yes')
notebook.pressed_index = None
# create a child frame for each page
frameOne = Tkinter.Frame(notebook, bg='white',width=560, height=100)
frameOne.pack(fill='both', expand=True)
# create the pages
notebook.add(frameOne, text='Simple calculation')
#Login Starts
failure_max = 8
passwords = [('name','password')]
def make_entry(parent, caption, width=None, **options):
tk.Label(parent, text=caption).pack(side=tk.TOP)
entry = tk.Entry(parent, **options)
if width:
entry.config(width=width)
entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH)
return entry
def enter(event):
check_password()
def check_password(failures=[]):
if (user.get(), password.get()) in passwords:
root.destroy()
return
failures.append(1)
if sum(failures) >= failure_max:
root.destroy()
raise SystemExit('Unauthorized login attempt')
else:
root.title('Try again. Attempt %i/%i' % (sum(failures)+1, failure_max))
parent = Tkinter.Frame(notebook, padx=10, pady=18, bg='white')
parent.pack(fill=tk.BOTH, expand=True)
user = make_entry(parent, "User name:", 16, show='')
password = make_entry(parent, "Password:", 16, show="*")
b = tk.Button(parent,borderwidth=4,text="Login",width=10,pady=8,command=check_password)
b.pack(side=Tkinter.BOTTOM)
password.bind('<Return>', enter)
#Close Application Button
def quit(root):
root.destroy()
tk.Button(root, text="Close Application", command=lambda root=root:quit(root)).pack()
#Calculation Starts
def defocus(event):
event.widget.master.focus_set()
def multiply(*args):
try:
product.set(round(float(Num_One.get())*float(Num_Two.get())))
except ValueError:
pass
Num_One = StringVar()
Num_Two = StringVar()
product = DoubleVar()
ttk.Label(frameOne, text="Select First Number:").grid(column =3, row = 0)
NumOne_Select = Combobox(frameOne, values=("1", "2", "3","4", "5"),textvariable=Num_One)
NumOne_Select.grid(column=4, row=0, columnspan="5", sticky="nswe")
Num_One.trace("w", multiply)
ttk.Label(frameOne, text="Select Second Number:").grid(column =3, row = 6 )
NumTwo_Select = Combobox(frameOne, values=("1", "2", "3","4", "5"),textvariable=Num_Two)
NumTwo_Select.grid(column=4, row=6, columnspan="5", sticky="nswe")
Num_Two.trace("w", multiply)
ttk.Label(frameOne, text = "Product:").grid(column = 3, row = 8)
ttk.Label(frameOne, textvariable=product).grid(column = 4, row = 8)
user.focus_set()
parent.mainloop()
root.mainloop()
You have several things going wrong in your code:
you're calling mainloop twice; you should only ever call it once.
you shouldn't pack or grid widgets inside the notebook. You are packing a widget and then using notebook.add; omit the pack.
you are calling destroy on the root window if the password is good. This causes your application to exit. Don't call destroy.
Normally the way this is done is that the notebook is a child of the root window, and the username/password dialog is an instance of Toplevel. You can hide the root window and pop up the dialog, and then if the user logs in, you can destroy the dialog and un-hide the main window.

Storing plot objects in a list

I asked this question yesterday about storing a plot within an object. I tried implementing the first approach (aware that I did not specify that I was using qplot() in my original question) and noticed that it did not work as expected.
library(ggplot2) # add ggplot2
string = "C:/example.pdf" # Setup pdf
pdf(string,height=6,width=9)
x_range <- range(1,50) # Specify Range
# Create a list to hold the plot objects.
pltList <- list()
pltList[]
for(i in 1 : 16){
# Organise data
y = (1:50) * i * 1000 # Get y col
x = (1:50) # get x col
y = log(y) # Use natural log
# Regression
lm.0 = lm(formula = y ~ x) # make linear model
inter = summary(lm.0)$coefficients[1,1] # Get intercept
slop = summary(lm.0)$coefficients[2,1] # Get slope
# Make plot name
pltName <- paste( 'a', i, sep = '' )
# make plot object
p <- qplot(
x, y,
xlab = "Radius [km]",
ylab = "Services [log]",
xlim = x_range,
main = paste("Sample",i)
) + geom_abline(intercept = inter, slope = slop, colour = "red", size = 1)
print(p)
pltList[[pltName]] = p
}
# close the PDF file
dev.off()
I have used sample numbers in this case so the code runs if it is just copied. I did spend a few hours puzzling over this but I cannot figure out what is going wrong. It writes the first set of pdfs without problem, so I have 16 pdfs with the correct plots.
Then when I use this piece of code:
string = "C:/test_tabloid.pdf"
pdf(string, height = 11, width = 17)
grid.newpage()
pushViewport( viewport( layout = grid.layout(3, 3) ) )
vplayout <- function(x, y){viewport(layout.pos.row = x, layout.pos.col = y)}
counter = 1
# Page 1
for (i in 1:3){
for (j in 1:3){
pltName <- paste( 'a', counter, sep = '' )
print( pltList[[pltName]], vp = vplayout(i,j) )
counter = counter + 1
}
}
dev.off()
the result I get is the last linear model line (abline) on every graph, but the data does not change. When I check my list of plots, it seems that all of them become overwritten by the most recent plot (with the exception of the abline object).
A less important secondary question was how to generate a muli-page pdf with several plots on each page, but the main goal of my code was to store the plots in a list that I could access at a later date.
Ok, so if your plot command is changed to
p <- qplot(data = data.frame(x = x, y = y),
x, y,
xlab = "Radius [km]",
ylab = "Services [log]",
xlim = x_range,
ylim = c(0,10),
main = paste("Sample",i)
) + geom_abline(intercept = inter, slope = slop, colour = "red", size = 1)
then everything works as expected. Here's what I suspect is happening (although Hadley could probably clarify things). When ggplot2 "saves" the data, what it actually does is save a data frame, and the names of the parameters. So for the command as I have given it, you get
> summary(pltList[["a1"]])
data: x, y [50x2]
mapping: x = x, y = y
scales: x, y
faceting: facet_grid(. ~ ., FALSE)
-----------------------------------
geom_point:
stat_identity:
position_identity: (width = NULL, height = NULL)
mapping: group = 1
geom_abline: colour = red, size = 1
stat_abline: intercept = 2.55595281266726, slope = 0.05543539319091
position_identity: (width = NULL, height = NULL)
However, if you don't specify a data parameter in qplot, all the variables get evaluated in the current scope, because there is no attached (read: saved) data frame.
data: [0x0]
mapping: x = x, y = y
scales: x, y
faceting: facet_grid(. ~ ., FALSE)
-----------------------------------
geom_point:
stat_identity:
position_identity: (width = NULL, height = NULL)
mapping: group = 1
geom_abline: colour = red, size = 1
stat_abline: intercept = 2.55595281266726, slope = 0.05543539319091
position_identity: (width = NULL, height = NULL)
So when the plot is generated the second time around, rather than using the original values, it uses the current values of x and y.
I think you should use the data argument in qplot, i.e., store your vectors in a data frame.
See Hadley's book, Section 4.4:
The restriction on the data is simple: it must be a data frame. This is restrictive, and unlike other graphics packages in R. Lattice functions can take an optional data frame or use vectors directly from the global environment. ...
The data is stored in the plot object as a copy, not a reference. This has two
important consequences: if your data changes, the plot will not; and ggplot2 objects are entirely self-contained so that they can be save()d to disk and later load()ed and plotted without needing anything else from that session.
There is a bug in your code concerning list subscripting. It should be
pltList[[pltName]]
not
pltList[pltName]
Note:
class(pltList[1])
[1] "list"
pltList[1] is a list containing the first element of pltList.
class(pltList[[1]])
[1] "ggplot"
pltList[[1]] is the first element of pltList.
For your second question: Multi-page pdfs are easy -- see help(pdf):
onefile: logical: if true (the default) allow multiple figures in one
file. If false, generate a file with name containing the
page number for each page. Defaults to ‘TRUE’.
For your main question, I don't understand if you want to store the plot inputs in a list for later processing, or the plot outputs. If it is the latter, I am not sure that plot() returns an object you can store and retrieve.
Another suggestion regarding your second question would be to use either Sweave or Brew as they will give you complete control over how you display your multi-page pdf.
Have a look at this related question.